title: Tweetable Mathematical Art

text:
# Question
Title: Tweetable Mathematical Art
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);

```

```
/* 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;

```

# The Rules

* Given this C++ code, 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 using unsigned chars instead of unsigned shorts.

Michaelangelo has provided a cleaned up 24-bit or 48-bit color output 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
## 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:

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

```
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);
}

```
> 120 votes

# 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;
}

```

# 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;
}

```

# 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;
}

```

# 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;}

```
> 208 votes

# Answer
## Random painter

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

And then we can slowly change the colours, where the overflows result in abrupt changes which make this look even more like brush strokes

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

## 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** 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!)
> 190 votes

# Answer
# Some swirly pointy things

Yes, I knew exactly what to name it.

```
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:

```
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.
> 162 votes

# Answer
Of course, there has to be a Mandelbrot submission.

```
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;

```

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
> 122 votes

# Answer
# Julia sets

If there's a Mandelbrot, there should be a Julia set too.

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

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:

Now let's add a simple red pattern to fill the void. Not really imaginative, but I'm not a graphic programer ... yet :-)

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

# 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;
}

```
> 107 votes

# Answer
```
/* 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);

```
> 103 votes

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

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):

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.

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;
}

```

This one looks a bit like a faded photograph... I like that.
> 81 votes

# Answer
# Sierpinski Pentagon

You may have seen the 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 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.

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:
> 76 votes

# Answer
# Sheet Music

Sierpinski music. :D The guys on chat say it looks more like the punched paper for music boxes.

```
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:

So yeah, that's interesting.
> 73 votes

# Answer
# Random 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.

# Edit:

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`

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.

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

## 4th: scanlines

Just kidding, this is not wanted but kind of cool, methinks.

Still working on reducing the size of the algorithm, I am proud to present:

### StarFox edition

### Voronoi instagram

## 5th: increase the number of points

I have now a working piece of code, so let's go from 25 to 60 points.

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:

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.**
> 60 votes

# Answer
The Lyapunov Fractal

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)

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);

```

**EDIT**

After much pain I finally got around to creating a gif of the second image morphing. Here it is:
> 57 votes

# Answer
Because unicorns.

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);
}

```
> 54 votes

# Answer
## Logistic Hills

## 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).
> 52 votes

# Answer
# Diffusion Limited Aggregation

I've always been fascinated by 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];}

```

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.

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];}

```

This can be animated in the same way as before:
> 50 votes

# Answer
# Spiral (140 exactly)

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.

Here, the gradient has been removed:

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):

And, here's the imgur album 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 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:
> 50 votes

# 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, 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;

```

---

I happened to stumble upon an edit by 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;

```
> 47 votes

# Answer
# Action Painting

I wanted to try recreating something similar to the work of 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. Huge thanks to:

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}

```

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.

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

# Answer
Figured I'd play with this code's parameters... All credit goes to @Manuel Kasten. These are just so cool that I couldn't resist posting.

```
/* 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

```
/* 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

```
/* 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

```
/* 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);

```
> 43 votes

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

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:

You can see these ripples in the image after regions which look very "flat" in colour.

Of course, using only one colour is boring.

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);
}

```
> 41 votes

# Answer
This calculates the 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);
}

```
> 41 votes

# 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:

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

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

```
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
> 38 votes

# Answer
# groovy

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`.
> 37 votes

# 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:

Pseudo-random pixels:

And, of course, a host of other possible results depending on your compiler, computer, memory manager, etc.
> 36 votes

# Answer
I'm not good at math. I was always poor student at math class. So I made simple one.

I used modified user1455003's Javascript code. And this is my full code.

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

---

```
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
> 33 votes

# 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, 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.
> 31 votes

# 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;
}

```

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;
}

```

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);

```
> 30 votes

# 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

## `w` = 360

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

---

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

# Answer
## Om nom nom

Continuing on my "classic games" theme, here's another entry... but not with pixel-art this time.

Better code management gave me space for more features, so it now features Inky, and also better colours and anti-aliasing. However, the suppression of the final cut-off dot had to go.

```
// RED
#define C(J,R)(sqrt(_sq((i+R)%(2*R)-R)+_sq(j-J))<R)
#define D(M,A,B)abs(i-M*50)<51?c?c-1?B:A:
#define Z 5;c%=3)v+=GR(3*i+k/3,3*j+k%3);return

// GREEN
int a=(i+30)/60%2,b=(i+150)/300;return b-1?C(1686,30)?b%2*a:C(1536,30)?a:abs(j-1611)<75?b%2:b%2*C(1536,150):C(1536,150)*(i-300<abs(j-1536));

// BLUE
static int c,v,k;for(c++,v=0,k=-4;k++<Z(D(2,1,1)0:D(6,1,0)0:D(10,1,.5).9:D(14,0,1).9:D(18,1,.7).2:1)*v*113;
#define RD BL
#define GR BL

```
> 28 votes

# Answer
**Colorful**

```
Red:

function(i,j) {return (i+j)/4%256;}

Green:

function(i,j) { return (i+2*j)/4%256; }

Blue:

function(i,j) { return (2*i+j)/4%256; }

```

**Diabolical**

In this, I defined `rad(x,y) = Math.sqrt(x*x + y*y);`

```
Red:

function(i,j) {return abs(floor(255*sin(0.5*rad(i-512,j-512)*2))+i)%256;}

Green:

function(i,j) { return 0; }

Blue:

function(i,j) { return 0; }

```

**Construction Papers**

```
Red:

function(i,j) {return (i%j)%256;}

Green:

function(i,j) { return (i*1.2%j)%256; }

Blue:

function(i,j) { return (i*1.5%j)%256; }

```

Adding one more..

**Cross on a hill**

```
Red:

function(i,j) {
  if(i>500&&i<524&&j>300&&j<600||i>400&&i<624&&j>400&&j<424)return 192;
  if((1024-j)>425*cos((i-512)*0.2))return 126;return 0;
}

Green:

function(i,j) {
  if(i>500&&i<524&&j>300&&j<600||i>400&&i<624&&j>400&&j<424)return 64;
  if((1024-j)<425*cos((i-512)*0.2))return 200;return 192;
}

Blue:

function(i,j) {
  if(i>500&&i<524&&j>300&&j<600||i>400&&i<624&&j>400&&j<424)return 0;
  if((1024-j)>425*cos((i-512)*0.2))return 238;return 0;
}

```
> 26 votes

# Answer
## Binary Flash (C++)

Here's one I made with a modified version of your framework, since I apparently don't have a reasonable ppm viewer. This one uses lodepng. *But first*, the submission:

```
unsigned short red_fn(int i,int j){
    double a=DM1-sqrt(_sq(i-DIM/2)*_sq(j-DIM/2)/8);return a<0?0:a;
}
unsigned short green_fn(int i,int j){
    return (unsigned short)((i^j)/9*sqrt(_sq((i-DIM/2)/10.)*_sq((j-DIM/2)/10.)))%DM1/(1+3.*(i+j)/DIM);
}
unsigned short blue_fn(int i,int j){
    return i&(~_sq(i/(j/10+1))|j);
}

```

(the quality of these uploads sucks apparently, so run the code yourself to see the result in its full glory)

## Triangular Limbo

I thought it couldn't hurt to submit a second one, a (thorough) modification of Binary Flash. Behold.

```
unsigned short red_fn(int i,int j){
    return 256+128+( (int)(256*sin(5.*i/DIM*acos(-1)))^(int)(256*sin(5.*j/DIM*acos(-1))) )/(1+1.*(i+j)/DIM);
}
unsigned short green_fn(int i,int j){
    return (int)(sqrt((i&(j-i))^j)/9*sqrt(_sq((i-DIM/2)/10.)*_sq((j-DIM/2)/10.)))%DM1/(7-2.*(i+j)/DIM);
}
unsigned short blue_fn(int i,int j){
    return i<j?((int)sqrt(i*i+j*j)^(i&j/(i*j+1)))/2:(i&(j-i))^j;
}

```

My framework is as follows: (C++ code)

```
#include <stdlib.h>
#include <math.h>
#include <vector>
#include "lodepng.h"
#define DIM 1024
#define DM1 (DIM-1)
#define _sq(x) ((x)*(x))                           // square
#define _cb(x) abs((x)*(x)*(x))                    // absolute value of cube
#define _cr(x) (unsigned short)(pow((x),1.0/3.0))  // cube root

//HERE COME YOUR FUNCTIONS

int main(){
    int i,j;
    std::vector<unsigned char> image;
    image.resize(4*DIM*DIM);
    for(j=0;j<DIM;j++){
        for(i=0;i<DIM;i++){
            image[4*(DIM*j+i)]=(double)(red_fn(i,j)&DM1)/DM1*255; //this is essentially the same as yours except that it transforms the [0,1023] range to [0,255] for lodepng
            image[4*(DIM*j+i)+1]=(double)(green_fn(i,j)&DM1)/DM1*255;
            image[4*(DIM*j+i)+2]=(double)(blue_fn(i,j)&DM1)/DM1*255;
            image[4*(DIM*j+i)+3]=255;
        }
    }
    lodepng::encode("MathPic.png",image,DIM,DIM);
    return 0;
}

```
> 25 votes

# Answer
## Sharp Edges

Not safe for children.

## The code

```
unsigned char RD(int i,int j){
    if(j<0){int k=9;while(1){if(i%(1<<k)==0){return k;}k--;}}return 255-(BL(i,(j+512)%DIM)|BL((i+512)%DIM,j));
}
unsigned char GR(int i,int j){
    #define d(x,y,z,w) sqrt(_sq(x-z)+_sq(y-w))
    #define A for(int k=8;k<DIM;k+=8){c[k]=RD(k,-1);}
    return BL((j+512)%DIM,i);
}
unsigned char BL(int i,int j){
    static int c[DIM];if(i+j<1){A}int p=0,k=0;if(j>512)j=DIM-j;for(;++k<DIM;){if(d(i,j,k,0)<pow(2,c[k]))p=1-p;}return 255*p;
}

```

I'm not really sure what to say about this one. There are a lot of ways to change the output based on this premise, but I can't find one that I personally find aesthetically pleasing.
> 24 votes

# Answer
# Projecting colors on a Hilbert curve

```
unsigned char RD(int i,int j){
    int x,y,s=DIM/2,d=0;for(;s>0;s/=2){x=(i&s)>0;y=(j&s)>0;d+=s*s*((3*x)^y);if(!y){if(x){i=DM1-i;j=DM1-j;}i=i+j-(j=i);}}return(d/4);
}

unsigned char GR(int i,int j){
    int x,y,s=DIM/2,d=0;for(;s>0;s/=2){x=(i&s)>0;y=(j&s)>0;d+=s*s*((3*x)^y);if(!y){if(x){i=DM1-i;j=DM1-j;}i=i+j-(j=i);}}return (d/32)>>2;
}

unsigned char BL(int i,int j){
    int x,y,s=DIM/2,d=0;for(;s>0;s/=2){x=(i&s)>0;y=(j&s)>0;d+=s*s*((3*x)^y);if(!y){if(x){i=DM1-i;j=DM1-j;}i=i+j-(j=i);}}return(d/32)>>7;
}

```

Or a little red:

```
unsigned char RD(int i,int j){
    int x,y,s=DIM/2,d=0;for(;s>0;s/=2){x=(i&s)>0;y=(j&s)>0;d+=s*s*((3*x)^y);if(!y){if(x){i=DM1-i;j=DM1-j;}i=i+j-(j=i);}}return(d/4);
}

unsigned char GR(int i,int j){
    return ((int)RD(i,j)/8)>>2;
}

unsigned char BL(int i,int j){
    return ((int)RD(i,j)/8)>>7;
}

```
> 21 votes

# Answer
# Be Happy

Palette is a little boring, but I don't have too much time to play with it and this is really just a novelty entry anyway.

edit -- this does seem to be OK on big endian machines. At least, i can traverse the pattern OK on one, so.... Thinking about it, I guess it makes sense; I'm only hard-coding the numerical values, not their bit representations.

```
unsigned char RD(int i,int j){
    uint16_t p[]={0x1ffc,0x0ff0,0x03c0,0x03c0,0x2184,0x3006,0x2184,0,0,0,0x0100,0x1188,0xa3c4,0x03c1,0x0ff0,0x3ff8};
    return p[j%16]&(1<<(i%16))?128:0;
}
unsigned char GR(int i,int j){
    return RD(i,j)?(i+j)/8:0;
}
unsigned char BL(int i,int j){
    return RD(i,j)?j/4:0;
}

```

I tweaked the pattern and used uint64\_t for grins, it made the data smaller (less commas and 0x characters) but the code to access the bits got bigger. So I had to split the data into a #define in the red function and then declare and use it in the green function. Then I tweaked the color palette to ensure each smiley was drawn entirely in the same color. I like this a little better....

```
unsigned char RD(int x,int y){
    #define d {0x44222002100C0FF0,0x800184218A514E71,0x4C39980980018001,0x7E00818318427E2}
    return GR(x,y)?(x/16)*15+(y/16)*15:0;
}
unsigned char GR(int x,int y){
    static uint64_t p[]=d;
    x%=16;y%=16;
    return p[y/4]&(((uint64_t)1)<<((y*16)%64+x))?128:0;
}
unsigned char BL(int x,int y){
    return GR(x,y)?(x/16)*32+(y/16)*10:0;
    #undef d
}

```

With this data line there's a little more separation between the smiley faces and I flipped the tertiary operator in the green function from "?128:0" to "?0:128" so it inverted the picture.

```
    #define d {0x1004080807F00000,0x400244224A522E72,0x27E4481240024002,0xFE010102188};

```

Ok, last one (I think, lol)...was bored, decided to see how far I could increase the size of the stipple map. Managed to get up to a 28x28 smiley with more #define trickery. The biggest tweak was the bit accessor, which could no longer take advantage of everything being evenly divided into 64 bits. To adjust, I had to compute the bit location in a separate variable, which bloated up the code 8 characters, pushing me really close to the edge.

So, here's the final image:

And the functions:

```
unsigned char RD(int x,int y){
    #define d1 {0,0xFFE000FFF00000F8,0x7FFFF007FFFF007F,0x80FDFBF80FFFFF00,0xFF81FDFBF80F9F9F,
    return BL(x,y)?(x/28)*15+(y/28)*15:0;
}
unsigned char GR(int x,int y){
    #define d2 0xFFFFC3FFFFFC1FFF,0x3FFFFFC3FFFFFC3F,0x781EFFF783FFFFF8,0xFFF00F3FCF80E7FE,
    return BL(x,y)?(x/28)*32+(y/28)*10:0;
}
unsigned char BL(int x,int y){
    uint64_t p[]=d1 d2 0x7F0FF007E43F00FD,0x3FC0001FFF800,0x1F00,0};
    x%=28;y%=28;
    int b=y*28+x;
    return p[b/64]&(((uint64_t)1)<<(b%64))?128:0;
}

```
> 21 votes

# Answer
## Simple raycaster (now with invaders)

I might update this with a more interesting scene/better golfing, but this'll do for now. The way the shim forward-declares the green and blue functions, implying they could be called from the red function, inspired me to abuse cross-method-body macros a bit.

The raycaster only supports a single channel, i.e. "bluescale". :-)

```
// RED
#define A X=1.*i/DM1-.5,Y=1.*j/DM1-.5,L=sqrt(X*X+Y*Y+4),d=L-10/L,I=1./0,a=2/Y*L-L,r=d*d-L*L-4,b=fmin(-d-sqrt(r),-d+sqrt(r))
return 0;

// GREEN
#define B c=fmin(a>0?a:I,b>0?b:I)
#define F(v)(int)(v*a/L+1e6)&1
return 0;

// BLUE
float A,B;
return((c-b?F(2*X)^F(-5):fmod(9+3*atan2(3-2*b/L,-X-X*b/L),2)<1^fmod(9-6*asin(-Y-b*Y/L),2)<1)?1:.5)*(c-b?c==I?0:2*Y/L:-(d+b))*DM1;

```
* The define in the red channel (`A`) performs camera calculations, sends the ray towards the sphere, and performs ray-sphere and ray-plane intersection.
* The define in the green channel (`B`) finds which of the shapes were the closest and defines a helper macro used for the checkerboard pattern of the floor.
* Finally, the resulting code in the blue channel performs UV mapping (the checkerboard pattern) and stitches it all together.

---

githubphagocyte suggested I try to incorporate a Space Invaders sprite in my raycaster answer, but I thought a simple texture would be boring so I tried to raycast some 3D pixel art instead... I messed up somewhere, though, so the result isn't perfect. I'm still pretty happy with the result though. The lighting this time around is completely fake.

```
// RED
#define A float X=1.*i/DM1-.5,Y=1.*j/DM1-.5,L=sqrt(X*X+Y*Y+4),c=32*L-L,N=g(X*c/L,Y*c/L)&0<c,M,a=N?c:1e9,b=16/L*N
#define R return
R BL(i,j);

// GREEN
#define g(u,v)"\x5F\xB6\x5C\x98"[abs((int)(u+1e3)%8-4)]>>(int)(v+1e3)%8&1
#define h(d,u,v)if(66>2*d/L&2*d/L>62&g(u,v)&0<d&d<a)a=d,b=.2
R 0;

// BLUE
A;for(i=-16;i<16;i++){N=1.0315*i/Y*L-L,M=(N+L)*Y/X-L;h(N,X*N/L,i)+Y/L;h(N,X*N/L,i-1)-Y/L;h(M,i,Y*M/L)+X/L;h(M,i-1,Y*M/L)-X/L;}R b*DM1;

```
> 21 votes

# Answer
# Cellular Automata Overlay

This submission chooses three faux-random elementary cellular automata and iterates one in each color channel, starting with a single pixel in the top center of the image and progressing downwards. Halfway down when some rules meet the side of the image there is some corruption of the expected pattern because of missing data outside the image.

The faux-randomness changes once per second and could use some better constants. Many of the CA rules result in patterns approximating Sierpinski's Triangle, but there are many other patterns including at least one chaotic pattern (#30).

Code:

```
unsigned short red_fn(int i,int j){
    static char p[1024][1026],e=e?e:257*time(0)&254|22;
    return (p[j][i+1]=(j<1?i==512:(e&1<<p[j-1][i]*4+p[j-1][i+1]*2+p[j-1][i+2])>0))*DM1;
}
unsigned short green_fn(int i,int j){
    static char p[1024][1026],e=e?e:511*time(0)&254|22;
    return (p[j][i+1]=(j<1?i==512:(e&1<<p[j-1][i]*4+p[j-1][i+1]*2+p[j-1][i+2])>0))*DM1;
}
unsigned short blue_fn(int i,int j){
    static char p[1024][1026],e=e?e:897*time(0)&254|22;
    return (p[j][i+1]=(j<1?i==512:(e&1<<p[j-1][i]*4+p[j-1][i+1]*2+p[j-1][i+2])>0))*DM1;
}

```

Example output:

Thank you to Martin Büttner for the idea to use static variables within the functions for persistence and pixel lookup!
> 20 votes

# Answer
# Starry Night (C#)

*Note: this uses RGB values 0...255*

**Image:**

**Code:**

```
    private ushort generateRed(int i, int j)
    {
        var value = (Math.Tan((i) * Math.Pow(i, Math.Sqrt(j) * 0.1))); return (ushort)(value > 255 ? 255 : (value < 0 ? 0 : value));
    }

    private ushort generateGreen(int i, int j)
    {
        var value = (Math.Tan((i) * Math.Pow(i, Math.Sqrt(j) * 0.1))); return (ushort)(value > 255 ? 255 : (value < 0 ? 0 : value));
    }

    private ushort generateBlue(int i, int j)
    {
        var value = (Math.Tan((i) * Math.Pow(i, Math.Sqrt(j) * 0.1))); return (ushort)(value > 255 ? 255 : (value < 0 ? 0 : value));
    }

```

The "stars" can be a little hard to make out so here is a link to the full-size image on imgur: https://i.stack.imgur.com/3o3Rd.png

Feel free to invent your own constellations from the image!
> 20 votes

# Answer
# Belousov-Zhabotinsky reaction

A simple simulation of this fascinating chemical reaction.

```
unsigned char RD(int i,int j){
#define R rand()%DIM
#define M m[(x+(d-1)%2+DIM)%DIM][(y+(d-2)%2+DIM)%DIM]
return(i+j)?140-BL(i,j)/3:0;}

unsigned char GR(int i,int j){
#define I if(m[x][y]==15)for(d=4;d--;)M
return(i+j)?80+BL(i,j)/3:0;}

unsigned char BL(int i,int j){static long m[DIM][DIM],n,x,y,d;if(i+j<1){for(n=1.2e8;n--;x=R,y=R){I=M?M:15;if(m[x][y])m[x][y]--;if(!(R||R))m[x][y]=15;}}return m[i][j]*16;}

```

The way the program works is simpler than you might expect. Each pixel is either zero, maximum, or somewhere in between.

* Zero: Nothing is happening but very occasionally spontaneously change to maximum
* Maximum: Will change any zero pixels adjacent to it to maximum, and then itself fade to maximum - 1
* Somewhere in between: Will fade by 1 until it reaches zero

This means that a point of maximum will spread out leaving a wake of somewhere in between behind it, which prevents it growing back against the direction of the wavefront.
> 18 votes

# Answer
# Playing with the Schwefel function

```
unsigned short RD(int i,int j){
    unsigned short res=0;
    res+=-i*sin(sqrt(i))+M_PI/2;
    res+=-j*sin(sqrt(j));
    res*=M_PI;
    res=abs(res)/DIM;
    return res;
}
unsigned short GR(int i,int j){
    unsigned short res=0;
    res+=-i*sin(sqrt(i)+M_PI/4*2);
    res+=-j*sin(sqrt(j));
    res*=M_PI;
    res=abs(res)/DIM;
    return res;
}
unsigned short BL(int i,int j){
    unsigned short res=0;
    res+=(-i*sin(sqrt(i)));
    res+=(-j*sin(sqrt(j)+M_PI/4*2));
    res*=M_PI;
    res=abs(res)/DIM;
    return res;
}

```

## Result

## Animation

**Done by adding (pi/4)\*k to the sin argument, with k iterating over \[0,8\] (a period)**
> 16 votes

# Answer
# Stripes

JavaScript, with appropriate definitions of `DIM` and some `Math` functions:

```
function RD(x,y){
  return x<0 ? 1+pow(round(((x+1)%DIM+DIM/2+1.5*BL(x,y))/(1+10*y/DIM)/5),3) : GR(sin(RD(x-DIM,y)),-1)
}

function GR(x,y){
  return y<0 ? floor(DIM*(1.5+x)/2.5) : GR(sin(1+RD(x-2*DIM,y)),-1)
}

function BL(x,y) {
  return x<0 ? 1.5*cos(x*x+y*y) : GR(sin(2+RD(x-3*DIM,y)),-1)
}

```

I had fun doubling up the uses of each function here. `RD` with a negative `x` computes the stripes, `BL` blurs the boundaries a little, and `GR` with a negative `y` scales the color values to the right range. If you look closely, you can see that the blurring is done independently for each color component:

Making the blur function a cosine wave instead gives a field of infinite lasagna:

```
function RD(x,y){
  return x<0 ? 1+pow(round((x+1+DIM/2+BL(x,y))/(0.25+10*y/DIM)/6),3) : GR(sin(RD(x-DIM,y))+1,-1)
}

function GR(x,y){
  return y<0 ? floor(DIM*(2+x)/4) : GR(sin(1+RD(x-DIM,y))+1,-1)
}

function BL(x,y) {
  r=y/cos(x/DIM+0.5); return x<0 ? 12*cos(16*sqrt(r))*r/DIM : GR(sin(2+RD(x-DIM,y))-0.5,-1)
}

```

Tweaking `RD` can make the width of the stripes nonlinear:

```
function RD(x,y){
  return x<0 ? 1+pow(round(((x+1)%DIM+DIM/2+BL(x,y))/(exp(3*y/DIM))/6),3) : GR(sin(RD(x-DIM,DIM-y))+0,-1)
}

function GR(x,y){
  return y<0 ? floor(DIM*(2+x)/4) : GR(sin(1+RD(x-2*DIM,DIM-y))+1,-1)
}

function BL(x,y) {
  return x<0 ? 1.5*cos(x*x+y*x)*y/256 : GR(sin(2+RD(x-3*DIM,DIM-y))-0,-1)
}

```

```
function RD(x,y){
  pi=acos(-1);return x<0 ? 1+pow(round((x+DIM/2+BL(x,y))/(cos(4*pi*(y/DIM-0.5)+pi)+2)/8),3) : GR(sin(RD(x-DIM,y)),-1)
}

function GR(x,y){
  return y<0 ? floor(DIM*(2+x)/4) : GR(sin(1+RD(x-DIM,y))-1,-1)
}

function BL(x,y) {
  return x<0 ? 0 : GR(sin(2+RD(x-DIM,y)),-1)
}

```

My favorite for last. This was a "beautiful mistake," when I was experimenting with different blur functions and made the amplitude really big. The full PNG is too ~~awesome~~ large for StackExchange, so here's the code, a JPG version, and a close-up:

```
function RD(x,y){
  return x<0 ? 1+pow(round(((x+1)%DIM+DIM/2+BL(x,y))/(0.25+10*y/DIM)/6),3) : GR(sin(RD(x-DIM,y))+1,-1)
}

function GR(x,y){
  return y<0 ? floor(DIM*(2+x)/4) : GR(sin(1+RD(x-2*DIM,y))+1,-1)
}

function BL(x,y) {
  return x<0 ? 21*cos(x*x+y*y)*pow(1+y/128,0.5) : GR(sin(2+RD(x-3*DIM,y))-0.5,-1)
}

```

Who knew that an unassuming `cos(x*x+y*y)` term could do that?!
> 15 votes

# Answer
# Fractal Carpets

I wanted to do Sierpinski's carpet, but dividing by 3 would be a bit of a pain in a 1024x1024 image. So--why not use a 4x4 pattern instead?

Full props to user1455003's JavaScript framework, since I don't have C++ available. I made a couple extra definitions to emulate the OP's macros:

```
var DIM = 1024;
var DM1 = DIM - 1;
var floor = Math.floor;

```

First, a plain blue 4x4 Sierpinski carpet:

```
function red(x,y){
  return 0
}

function green(x,y){
  return 0
}

function blue(x,y) {
  for(b=256;b>=1;b/=4){a='1111100110011111';m=floor(x%(b*4)/b);n=floor(y%(b*4)/b);if(a[m+4*n]<1)return 0}
  return DM1
}

```

(Open images in separate tab for full resolution.)

Next I tweaked the color scheme by giving squares a little color if they were removed in later steps:

```
function red(x,y){
  return 0
}

function green(x,y){
  return 0
}

function blue(x,y) {
  for(b=DIM/4,k=0;b>=1;b/=4,k++){a='1111100110011111';m=floor(x%(b*4)/b);n=floor(y%(b*4)/b);if(a[m+4*n]<1)break}
  return DM1*k/5
}

```

Now it's time to overlay different patterns for each color!

```
function red(x,y){
  for(b=DIM/4,k=0;b>=1;b/=4,k++){a='1111000100010001';m=floor(x%(b*4)/b);n=floor(y%(b*4)/b);if(a[m+4*n]<1)break}
  return DM1*k/5
}

function green(x,y){
  for(b=DIM/4,k=0;b>=1;b/=4,k++){a='0000011001100000';m=floor(x%(b*4)/b);n=floor(y%(b*4)/b);if(a[m+4*n]<1)break}
  return DM1*k/5
}

function blue(x,y) {
  for(b=DIM/4,k=0;b>=1;b/=4,k++){a='1000100010001111';m=floor(x%(b*4)/b);n=floor(y%(b*4)/b);if(a[m+4*n]<1)break}
  return DM1*k/5
}

```

Checkerboard: `1010010110100101, 0101101001011010, 0101101001011010`

`1001011001101001, 0000011001100000, 0110100110010110`

`0100001000100001, 0000011111100000, 0010010001001000`

Of course, we need some Sierpinski triangles too: `1111011100110001, 0001001101111111, 1000110011101111`
> 14 votes

# Answer
# Wavy Chessboard (Python)

```
DIM = 1024

def red(i, j):
    i+=sin(4*pi*j/DIM)*DIM/84;i=max(1,min(i,DIM-1))
    return ceil(4+sin(8*pi*i/DIM)*sin(8*pi*j/DIM)*3)*32

def green(i, j):
    return red(i,j)

def blue(i, j):
    return red(i,j)-cos(4*pi*i/DIM)*16

```

The code uses PIL to generate an image, so the functions return a value out of 256, not 1024.
> 13 votes

# Answer
# Because why not?

I happened to stumble upon a cool map. It iteratively applies cosine, sine, cosine, sine,.... starting with some initial value.

```
    unsigned short int RD(int i, int j){
        float x=i*j;for(int k=0;k++<15;){x=k%2==0?cos(x):sin(x);}return (DIM-1)*x;
    }
    unsigned short GR(int i,int j){
        float x=i*j;for(int k=0;k++<15;){x=k%2==0?cos(x):sin(x);}return (DIM-1)*x;
    }
    unsigned short BL(int i,int j){
        return 0;
    }

```

Also, remember Happy Numbers? Well, I thought it would be cool to see the distribution of the first 1048576 happy numbers. To fill the other two streams, I used happy numbers where we take the sum of the cubes of the digits instead of the squares, and Harshad Numbers.

```
    unsigned short int RD(int i, int j){
    int h=DIM*j+i+1;int t=h;for(int k=0; k<DIM; k++){int s=0;while(h!=0){s=s+_sq(h%10);h=h/10;}h=s;if(h==1)return DM1;if(h==t)break;}return 0;
    };
    unsigned short int GR(int i, int j){
    int h=DIM*j+i+1;int t=h;for(int k=0; k<DIM; k++){int s=0;while(h!=0){s=s+_cb(h%10);h=h/10;}h=s;if(h==1)return DM1;if(h==t)break;}return 0;
    };
    unsigned short int BL(int i, int j){
    int h=DIM*j+i+1;int s=0;int t=h;while(h!=0){s=s+h%10;h=h/10;}if(t%s==0)return DM1;return 0;
    }

```
> 12 votes

# Answer
# TweetArt - A Mac App

<sup>Sorry for the unoriginal, boring name</sup>

I created this app because if this contest is all about tweets, why not use some *actual* tweets from *actual* users? Just enter a @username to pull the first tweet from that user. From this tweet, the tweet then goes through an entropy generator (I'm not sure if that's the correct usage of the word but in this context it just means its randomness), which outputs a random number between 0 and 1024. If you run the same tweet through, you'll get the same number. This then can be used as sort of seed for a math function/equation, or used directly as a value.

For example:

* As the seed for `srand();` or another PRNG.
* Used to generate coordinates and a zoom level for a fractal.
* As the hue for a color. e.g. `e % 255 = color`.

The possibilities are endless!

So what else can this app do?

* Ability to add your own custom tweet
* Save as both PNG and BMP. So no need for any other applications to view your art.
* Fully C++ compatible wrapped in Objective C i.e. Objective C++.
* Supports multiple equations.
* Randomize equations to generate art truly random.
* Easily add new equations with the help of Objective-C's *awesome* built-in reflection support.

Here's a screenshot:

As you can see, Martin Buttner's art does not look exactly like his submission, but that's because I've modified it slightly to add the effects of entropy. I've included seven submissions from users whose submissions I particularly enjoyed. Not to discriminate of course but adopting an equation which I have absolutely no understanding of how it works, is time consuming so I stopped at seven.

So how do I add an equation you might be wondering? Well there are just a few simple steps:

1. In ArtEquations.h, copy and paste the three methods for each channel and change the number to the next number in the list. For example, adding one new art thing will add three new methods called:

```
 -(unsigned char)r8WithEntropy:(int)e column:(int)i row:(int)j;
 -(unsigned char)g8WithEntropy:(int)e column:(int)i row:(int)j;
 -(unsigned char)b8WithEntropy:(int)e column:(int)i row:(int)j;

```

If this syntax looks alien to you, it's pretty simple. `unsigned char` is the return type, and the words followed by colons make up the message name (in this example, the whole message name is `r8WithEntropy:column:row:`. The `(int)x` are the parameters associated with each message fragment. For each art thing you add, simply increment the number in the first message part by 1 r9, r10, r11, etc.

2) In ArtEquations.mm (the file extension for ObjC++ implementation files), under number of equations, increment that number to how every many art things you have (how intutive!).

3) In the EquationNames, add a name for your art using the syntax of `@"Name"`, and add it to the end before the bracket, and separate the names by commas.

4) At the bottom of the file, paste in the three methods you added from step 1., and replace the semicolons with open and closed braces.

5) Inside those braces, add your C++ code! Add all your C++ goodness right inside that Objective-C method. Cool right? If you need to call say r8 from g8, feel free to define a Macro for it with the syntax of: `#define RD(I,J) [self r8WithEntropy:e column:I row:J]`. And replace `RD` with whatever you need and `r8` with whatever channel you need.

6) And that's it! That's all you need. run the application and your art thing should show up right in the picker.

If you don't have Xcode, see this link for how to compile an Xcode project from the command line.

Please fork this! Add your own art stuff with a new entropy parameter, and contribute to this post! Add in your methods and what tweet generated that cool art! The github project link is at the top of this post. Once you fork and add new stuff, just add a comment so I can merge the changes and update the download link for the built and runnable app.

Todo:

* I can currently use only unsigned chars. If anyone wants to figure out how to use unsigned shorts, please fork and comment. I'll gladly merge.
* Maybe pull code directly from this website??? :)
* Add as many arts as I can!
* Clear const values after generation. Currently, because this doesn't just exit after generation as in the other ones, consts aren't cleared. If anyone knows how to clear them, please tell me.

Here's a few pictures I saved, feel free to add more. I don't actually have the tweets, but if you add more, please add the tweets and functions so we can generate them ourselves :)

Also I'd like to give credit to faubiguy because I used his art in the icon:

# TweetArt Download Link
> 10 votes

# Answer
# Simple StackOverflow "Logo"

(i know it would be a terrible logo, but i don't know how to call it)
Definitely not something as cool as rest of images - it's rather proof concept that i made to check whether it is possible to place some text (in this case shortcut of "stackoverflow" - letters "SO") on image and draw something more interesting than very simple background. C++ version, compiled and tested on Mac OS X 10.9.3 with clang.

```
unsigned short RD(int i,int j){
    int d=sqrt(8*_sq(i-450)+_sq(j-450));
    return(((GR(i,j)>254||BL(i,j)>254))|(d<=100&d>80&i<=450))*255;
}
unsigned short GR(int i,int j){
    int d=sqrt(8*_sq(i-575)+_sq(j-540));
    return(d<=190&d>170)?255:fmin(254, (10*(j+150.*sin(j*15./DIM))/++i));
}
unsigned short BL(int i,int j){
    int d=sqrt(8*_sq(i-450)+_sq(j-630));
    return(((GR(i,j)>254))|(d<=100&d>80&i>=450))?255:fmin(254, 8*(DIM-i)/++j);
}

```

To run just copy this code inside "framework" and run:

```
clang++ code_golf_tweetable_math_art.cpp -std=c++11 && ./a.out && convert MathPic q.bmp && open q.bmp

```

Note that you have to have Image Magick installed and MathPic file created.
> 9 votes

# Answer
# Plaid Trip

```
unsigned char RD(int i,int j){
    return i<512||j<512?4096*sin((i/((j%512)+1)))+1024*sin((j/((i%512)+1))):sqrt(4096*sin((i/((j%512)+1)))*1024*sin((j/((i%512)+1))));
}
unsigned char GR(int i,int j){
    i=(1023-i);
    return 2048*sin((i/((j%256)+1)))-512*sin((j/((i%256)+1)));
}
unsigned char BL(int i,int j){
    i+=1024;j+=1024;
    return 1024*sin((i/((j%128)+1)))-256*sin((j/((i%128)+1)));
}

```
> 9 votes

# Answer
# Marbelous

The actual output image is rather mundane compared to other entries here, the equivalent of about 25 bytes of C. I had more fun writing the main loop than the R/G/B functions.

Note that spaces between cells are optional, included here for clarity. The Gren function is actually 53 bytes of code, and the other two about that much combined. There's definitely more that could be done with the remaining space, since I've only used about 1/4 of it in total. Specifically:

Multiplication may be more compact with bit shifts instead of decrements.

I haven't added square or cube or cube root helpers, as the challenge allows.

I haven't made use of recursion.

PS: My main function only makes a 256x256 image because Marbelous is an 8 bit language. I could easily modify the program to output 16 tiled copies of the result. Making it operate on 10-bit integers would be significantly more challenging (and would require a faster interpreter).

```
# generates a 256x256 24bit RGB image
# pseudocode:
# print "P6\n256 256 255\n"
# for y in range(256)
#  for x in range(256)
#   print Redd(y,x)
#   print Gren(y,x)
#   print Blue(y,x)
.. .. .. .. .. .. P0 P1 .. .. .. .. .. ..
.. .. .. .. P2 .. 00 // .. .. PX PY .. ..
.. .. .. .. .. Nx /\ .. .. .. Ba il .. ..
.. .. .. .. 00 P0 .. /\ .. .. XX .. .. ..
.. .. .. P2 /\ .. PA .. /\ .. .. .. .. ..
.. .. .. .. .. // .. PB .. PC .. .. .. ..
.. .. .. .. /\ .. .. .. .. .. .. .. .. ..
.. .. PD /\ PE \\ PF .. .. .. .. .. .. ..
.. .. .. PA .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. PB .. .. .. .. .. .. .. ..
.. .. .. .. PE .. PF .. PC .. 32 35 35 0A
.. PD .. .. .. .. .. .. /\ .. 32 35 36 20
PX /\ .. .. .. .. .. .. .. PY 32 35 36 20
.. .. Re dd Gr en Bl ue .. .. 50 36 0A ..
.. .. .. .. .. .. .. .. .. .. .. .. .. ..
:Nx
# O0 = I0+1
# overflow bit to the left side
I0 00 01
++ O< S0
=0 S0 O<
O0 O0 ..
:Bail
# if I0==255 and I1==255 then output 1
I0 .. I1 ..
++ .. ++ ..
=0 ++ =0 ..
XX O0 XX O0
:Redd
# ((I0/2)+(~I1))*4
I0
>> I1
.. !!
.. //
<<
<<
O0
:Gren
# I0*I1
I0 P0 .. P1 I1
\\ >0 S0 \\ S0
.. S1 -- 00 /\ P1
.. \/ P0 S1
.. .. .. O0
:Blue
# ((I0)+(I1/2))*4;
I1
>> I0
.. //
<<
<<
O0

```
> 7 votes

# Answer
# Powers FTW!

Returning to the question's language, I started playing about with `pow()`. These images look better than my Python submissions because I was programming on my phone. I just got bored after waiting five minutes for a random scattering of dots to be generated so I posted the best of the lot.

One thing led to another, and suddenly some nice looking stripes appeared. The ppm looks nicer than the png, I think Imagemagick messed it up a bit...

```
unsigned short RD(int i,int j){
    return pow(i+j, 0.25);
}
unsigned short GR(int i,int j){
    return pow(i+j, 0.5);
}
unsigned short BL(int i,int j){
    return pow(i+j, 1/3);
}

```

I stayed with `pow()`, finding nice patterns as the different frequencies overlapped. This time I didn't go for nth root, making it a lot harder to get a decent image. Eventually, using small numbers worked.

```
unsigned short RD(int i,int j){
    return pow(1.009, i-j)+pow(1.008, i+j);
}
unsigned short GR(int i,int j){
    return pow(1.01, i-j)+pow(1.007, i+j);
}
unsigned short BL(int i,int j){
    return pow(1.02, i-j)+pow(1.006, i+j);
}

```

## Edit:

Thanks to Milo, he notified me that when I was performing the cube root, I wasn't formatting it as a float. Here's the updated image and code:

```
unsigned short RD(int i,int j){
    return pow(i+j, 0.25);
}
unsigned short GR(int i,int j){
    return pow(i+j, 0.5);
}
unsigned short BL(int i,int j){
    return pow(i+j, 1.0/3.0);
}

```
> 6 votes

# Answer
# JavaScript

Use code like that of user1455003 to view these full-scale.

## 101

```
function red(x,y){
    return (x*y) % 1024;
}
function green(x,y){
    return x-y;
}
function blue(x,y) {
    return (x+y) % 1024;
}

```

## 202

```
function red(x,y){
    return x*Math.cos(x);
}
function green(x,y){
    return y*Math.cos(y);
}
function blue(x,y) {
    return x*y/Math.tan(x*y) % 1024;
}

```

In full scale, the red and green don't form these stripes, they're just gradients over a series of thin lines. For compensation, the blue patterns look more intriguing, especially in the upper left corner.

## Sparkling

```
function red(x,y){
    return 0.7*(Math.pow(3.25, Math.log(x*y)) % 1024);
}
function green(x,y){
    return 0.3*(Math.pow(2.75, Math.log(Math.pow(Math.log(x),Math.log(y)))) % 1024);
}
function blue(x,y) {
    return Math.pow(3, Math.log(x*y)) % 1024;
}

```
> 5 votes

# Answer
# How about Python?

I don't if I've followed your code exactly, but here's what I've managed to put together:

```
import Image, math

# Functions here

img = Image.new('RGB', (1024, 1024), "black")
pixels = img.load()

for i in range(img.size[0]):
    for j in range(img.size[1]):
        pixels[i, j] = (r(i,j),g(i,j),b(i,j))

img.save('/storage/emulated/0/image.jpg', 'JPEG')

```

## Argyle Christmas Sweater - 177 chars

```
def r(x,y):
    return int(math.tan(x+y))
def g(x,y):
    return int(math.tan(x-y))
def b(x,y):
    return int(math.tan(x*y))

```

I don't exactly know what the blue does... The pattern is nice though.

## Christmas Stars/Snow - 102 chars

As you can see, I'm keeping to a Christmas theme. You either interpret this as a starry night or snow falling.

```
def r(x,y):
    return int(math.tan(x*y)*10)
def g(x,y):
    return r(x,y)
def b(x, y):
    return r(x,y)

```
> 4 votes

# Answer
# Zebra Stripes

Ugh, lol this challenge is killing me and my work productivity, haha! Good thing it's slow right now.

Anyway, stealing from the random ideas; this guy walks the blue up or down a small amount. After half a row in the same "direction" (512 "stable" pixels), it has a 25% chance of "turning around". The red and green use the same generator. Result:

With the red "out of phase", it makes for some colorful stripes (which I personally like better). To get this, just add 128 to the return value of the red function.

Toying with placing the red/green out of phase different amounts yields various other results. Here, I subtract 50 from the red and add 95 to the green.

Here's the code:

```
unsigned char RD(int i,int j){
    #define M if(s++>512){d*=(rand()%1000)>750?-1:1;s=0;}c+=(rand()/1./RAND_MAX)*(float)d;
    return BL(i,j);
}
unsigned char GR(int i,int j){
    #define C if(c>255||c<0){d*=-1;c+=d;s=0;}
    return BL(i,j);
}
unsigned char BL(int i,int j){
    static float c=0;static int d=1,s=0;
    M C return((int)c);
}

```

If you find any neat alignments for red/green, post 'em in the comments! You can also toy with the constants in M; the \>512 changes the "stability" (it'll be less likely to have long strings of increasing/decreasing intensities) while the \>750 is 750/1000 (75%) chance (due to the %1000 on rand) the direction stays the same (or 25% chance it changes, depending on how you look at it).

Creating something "nice" and interesting takes some balancing of the stability and random chance it switches after reaching stability. For example, with the last example, taking the "stability" down to 100 makes the image look like this:

While the original, with the chance for change up'd to 90% (replace \>750 with \>100), creates this:

Have fun! I *think* I'm done now, haha. I'm beginning to have a love/hate relationship with this challenge, lol!
> 3 votes

# Answer
# JavaScript

Use user1455003's code to display the image.

```
function red(x, y) {
    return (x - Math.cos(y)) % 256;
}

function green(x, y) {
    return (Math.sqrt(x * y)) % 256;
}

function blue(x, y) {
    return Math.sqrt(x + y + x * y) % 256;
}

```
> 2 votes

# Answer
# Generated by tweets

I had no idea what to do, but I wanted to participate.

So I though that I could transform tweets into formulae.

I take the first tweet searching for red/green/blue and transform letters into cos/sin/i/j/digits. Then depending on the number, I add or mult\ iply to the next item. I then shorten the formula to be ≤140.

Results are pretty poor though… The transformation should be improved to include more operations, but I had fun.

Sometimes, during compilation, I have:

```
warning: integer overflow in expression [-Woverflow]

```

Sample functions:

```
return fmod((114*i+100*i+109*i+cos(99)*j+cos(110)*122*cos(sin(sin(sin(sin(sin(sin(sin(sin(cos(cos(110)))))))))))*98*115*112),1024);}
return fmod((109*112*sin(cos(i))+100*104*233*114*i+114*i+cos(224)*cos(108)*cos(cos(sin(sin(sin(cos(85))))))*77*80),1024);}
return fmod((114*i+100*i+109*i+cos(99)*j+cos(110)*122*cos(sin(sin(sin(sin(sin(sin(sin(sin(cos(cos(110)))))))))))*98*115*112),1024);}
return fmod((j+114*100*i+110*76*j+j+i+115*i+114*i+100*cos(cos(cos(i)))+108*j+115*109*cos(106)*j+j+114*100*i+110),1024);}
return fmod((cos(cos(114))*sin(103)*84*sin(sin(cos(110)))*98*115*112*sin(cos(79))*108*j+119*i+sin(j)+114*116*i+115*84*119*i+i+116),1024);}
return fmod((cos(116)*cos(115)*cos(103)*i+110*103*103*114*i+i+110*98*j+j+j+j),1024);}

```

Some images:

I will update if I generate more interesting patterns.

Oh, almost forgot the python code:

```
from requests import session
from BeautifulSoup import BeautifulSoup

s = session()
r = BeautifulSoup(s.get('https://twitter.com/search?q=red&src=typd').content)
g = BeautifulSoup(s.get('https://twitter.com/search?q=green&src=typd').content)
b = BeautifulSoup(s.get('https://twitter.com/search?q=red&src=typd').content)

def transform(t):
    l1 = [str(ord(i)) if (i not in 'aeiouy') else 'i' if i in 'aei' else 'j' for i in t]
    l2 = [i if (i in 'ij') or int(i)>75 else 'cos' if int(i)<50 else 'sin'  for i in l1]
    res = ''
    cpt = 0
    for l in l2:
        if l in ('sin','cos'):
            res += l + '('
            cpt +=1
        else:
            if l in 'ij':
                ope = '+'
            else:
                ope = '*'
            res += l+')'*cpt + ope
            cpt = 0
    res = res[-119:]
    while (res[0] not in '+*'):
        res = res[1:]
    while (res[-1] not in '+*'):
        res = res[:-1]
    return 'return fmod(('+res[1:-1]+'),1024);'

r,g,b = [i.findAll("p","js-tweet-text tweet-text") for i in (r,g,b)]

rgb = [transform(i.text) for i in (r[0],g[0],b[0])]

with open('filename.cpp', 'r') as f, open('filename.res.cpp', 'w') as g:
    for l in f:
        if('// YOUR CODE HERE' not in l):
            g.write(l)
        else:
            g.write(rgb[0])
            rgb=rgb[1:]

```
> 2 votes

---
Tags: math, popularity-contest, graphical-output
---