I've always liked screens full of randomly colored pixels. They're interesting to look at and the programs that draw them are fun to watch.

The challenge

Fill your screen, or a graphical window, with colored pixels.

The rules

  • Your program must have an even chance of picking all colors (i.e in the range #000000 to #FFFFFF), or all colors that can be displayed on your system.
  • Your program must continue to display random pixels until manually stopped (it cannot terminate on its own).
  • Pixels can be any size, as long as your output has at least 40x40 "pixels".
  • Your program must run at such a speed that it can replace every pixel on the screen/window at least once after running for three minutes.
  • Your program must choose truly random colors and points to replace, i.e. random with all points/colors equally likely. It cannot just look random. It must use a pRNG or better, and the output cannot be the same every time.
  • Your program must have an equal chance of picking all colors each iteration.
  • Your program must replace only one pixel at once.
  • Your program cannot use the internet nor your filesystem (/dev/random and /dev/urandom excepted).


Your output could look like this if stopped at a random time:

The winner

The shortest answer in each language wins. Have fun!

  • \$\begingroup\$ By "truly random", I assume pseudorandom is OK (like Math.random() or similar) \$\endgroup\$
    – AAM111
    Jun 2, 2017 at 1:29
  • \$\begingroup\$ @OldBunny2800 It must use a pRNG or better \$\endgroup\$ Jun 2, 2017 at 13:07
  • \$\begingroup\$ Since the program can't use the internet, I'll just leave this in a comment: babelia.libraryofbabel.info/slideshow.html \$\endgroup\$
    – KSmarts
    Jun 2, 2017 at 13:28
  • 1
    \$\begingroup\$ So does the "3 minute limit" apply to setup time, too? Or just once the "program" begins? Asking because I have a Minecraft redstone solution, which runs very quickly once it is going, but takes a while to set up initially (it has to "place" each "pixel" in the 40x40 grid) before it can start changing colors. \$\endgroup\$
    – BradC
    Jun 4, 2017 at 2:34
  • 5
    \$\begingroup\$ Truly random by definition exclude pseudo-random, yet doesn't define a distribution. I assume you mean a uniform PRNG, where all events are equiprobable and independent of each other. \$\endgroup\$
    – Dennis
    Jun 4, 2017 at 4:44

50 Answers 50


Commodore 64 (old ROM I think), ~28 tokenized BASIC Bytes used

 0poke646,rnd(.)*16:?"{reverse on} ";:goto

The memory location 646 is used as a colour out in the BASIC kernal (pretty sure this is the old kernal, not the C64c kernal), which is one of the 16 colours available in its palette. Then a reverse space is printed after. goto is used as an infinite loop until the screen is filled.

This is the cheapest in terms of bytes. There is a nicer way to do this, as follows:

Commodore 64 (new and old ROM), ~46 tokenized BASIC bytes

 0 fori=0to999:poke1024+i,160:poke55296+i,rnd(.)*16:next

This will poke firstly a reversed (or inversed) space to the screen RAM (at 0x0400 - 0x07e7), and then alter the colour attribute for each character position (mapped at 0xd800 - 0xdbe7) between 0 and 15 inclusive.

As soon as the for/next loop ends, the ready. prompt is shown. To stop this, add the following line, costing another 7 tokenized BASIC bytes:

 1 go to 1

Commodore C64 random colour generator simulator


Powershell, 128 126 124 88 bytes

-2 bytes thanks @Veskah

1..($c=[Console])::WindowWidth*$c::WindowHeight|%{Write-Host ' '-b(random 16)-n}



VS code output:

VS Code

  • 1
    \$\begingroup\$ Don't need the semi-colon and there's an extra space in the write-host \$\endgroup\$
    – Veskah
    May 8, 2019 at 13:22
  • 1
    \$\begingroup\$ not sure this satisfies the condition of overwriting every cell at least once within 3 minutes \$\endgroup\$
    – T3RR0R
    Oct 28, 2021 at 19:33
  • \$\begingroup\$ Thanks. Fixed. ¯\_(ツ)_/¯ \$\endgroup\$
    – mazzy
    Oct 28, 2021 at 20:01
  • \$\begingroup\$ Your latest edit is not functional for the terms of the challenge. \$\endgroup\$
    – T3RR0R
    Oct 28, 2021 at 21:08
  • 1
    \$\begingroup\$ A golf of your last working answer that brings it down to 105 bytes and ensures all cells can be rewritten within 3 minutes as required: mode 40,40;for(){[Console]::SetCursorPosition((random(40)),(random(40)));Write-Host ' '-b(random 16)-n} \$\endgroup\$
    – T3RR0R
    Oct 30, 2021 at 12:40

TI-Basic (83/84(+(SE)) only), 33 bytes

If int(2rand

where C is the name of the program.

Without calling itself (+2 bytes):

While 1
If int(2rand

The TI-83 family calculators with monochrome screens (TI-83, TI-83+, TI-83+SE, TI-84+, and TI-84+SE) support only black and white as colors. This program goes through all the pixels on the screen (except for the rightmost column and bottommost row) and has a 50% chance of inverting it. This may take more than 3 minutes depending on the calculator; if so, replacing 62 and 94 with 39 each should work.


R, 143 138 bytes

-4 bytes thanks to user2390246


image makes the required 40x40 grid of rectangles with a matrix m of values (fixed to be 1:1600 in a 40x40 square), with a randomly selected color for each rectangle, k. It plots the image, waits long enough to actually render the image, then randomly changes one of the colors. Uses hsv encoding since it is a value between 0 and 1, which allows us to use runif to generate random colors.

This generates a new plot each time.

  • \$\begingroup\$ It won't affect the score, but shouldn't image(x,x,m,c=k) be outside the while loop? \$\endgroup\$ Jun 2, 2017 at 12:31
  • \$\begingroup\$ I don't think you need to define m, you only use it once. \$\endgroup\$ Jun 2, 2017 at 12:34
  • 1
    \$\begingroup\$ @user2390246 for the image question, nah, it has to be re-called every time since it's really drawing a new image each time after changing one of the colors. Good call on the m, though. I originally thought I had to change that matrix and never went back and changed it. \$\endgroup\$
    – Giuseppe
    Jun 2, 2017 at 13:17

Java 7 with JavaFX, 686 674 bytes

import javafx.scene.*;import javafx.scene.canvas.*;import javafx.scene.layout.*;public class M extends javafx.application.Application{public static void main(String[]a){launch(a);}GraphicsContext g;public M(){}public void start(javafx.stage.Stage x){BorderPane r=new BorderPane();Canvas c=new Canvas(40,40);g=c.getGraphicsContext2D();Pane p=new Pane();p.getChildren().addAll(c);r.setCenter(p);x.setScene(new Scene(r,40,40));x.show();new javafx.animation.AnimationTimer(){public void handle(long n){M.this.g.setFill(javafx.scene.paint.Color.color(Math.random(),Math.random(),Math.random()));M.this.g.fillRect((int)(Math.random()*40),(int)(Math.random()*40),1,1);}}.start();}}


import javafx.scene.*;import javafx.scene.canvas.*;import javafx.scene.layout.*;
                                            // Required imports

public class M extends javafx.application.Application{
                                            // The class (NOTE: The public is mandatory for JavaFX)
  public static void main(String[]a){       //  Mandatory main method
    launch(a);                              //   Call the launch of the Application
  }                                         //  End of main-method

  GraphicsContext g;                        //  GraphicsContext on class-level which we'll use in the animation

  public M(){}                              //  Empty constructor (again, mandatory for JavaFX)

  public void start(javafx.stage.Stage x){  //  Overwritten start-method of Application
    BorderPane r=new BorderPane();          //   Create a BorderPane
    Canvas c=new Canvas(40,40);             //   Create a Canvas with the minimum size
    g=c.getGraphicsContext2D();             //   Retrieve the GraphicsContext and set it to the class-level variable
    Pane p=new Pane();                      //   Create a Pane
    p.getChildren().addAll(c);              //   Add the Canvas to the Pane
    r.setCenter(p);                         //   Put it in the center (otherwise it won't show in the window)
    x.setScene(new Scene(r,40,40));         //   Create a new Scene
    x.show();                               //   And show the screen
    new javafx.animation.AnimationTimer(){  //   Create a new animation
      public void handle(long n){           //    Overwritten handle-method of this animation
                                            //     Set a random color
                                            //     And add this color as a 1x1 pixel in a random position
      }                                     //    End of handle-method
    }.start();                              //   And start the animation
  }                                         //  End of start-method
}                                           // End of class


enter image description here


Mathematica 112 Bytes


Very straightforward, uses Dynamic around an ArrayPlot. Not terribly fast; limited by the maximum speed dynamic can update, but should fulfill the goal on most computers.

Starts out with a random 40x40 grid and recolors a random pixel one at a time. Ceiling characters are 3 bytes each, Ouch!


Ruby + ruby2d: 101+9 = 110 bytes

Uses the -rruby2d flag. 80x60 "pixel" image. Timed the module to run 100 update ticks in 2 seconds, so it theoretically replaces all pixels on the screen in under 2 minutes.


Processing.js, 142 bytes

for(var i=0;i<99;i++){for(var j=0;j<99;j++){fill(random(0,255),random(0,255),random(0,255),random(0,255));rect((i-1)*40,(j-1)*40,i*40,j*40);}}



Ruby, 78 Bytes


If you count the bytes you'll see that it's more than 78 bytes. That's because I had to replace the ASCII escape character (decimal value 27) with "\e" as stackexchange sanitizes the post. Both can be used in ruby code so the above code will work but for the purpose of golfing you can replace them with the literal escape character.

The code prints a box into the terminal at a random position from 0;0 to 40;40 with a random color.

The result will look something like this:

output on gnome terminal with the solarized color scheme

(result may vary depending on terminal and color scheme)


loop {                      # Loop forever
  print "                   # Prints one long string to the terminal     
    \e[                     # Start of an ANSI escape sequence. In this case it
                            # will move the cursor
    #{rand(41)};            # Random y position
      #{rand(41)}H          # Random x position
        \e[                 # Specify the color of the following character
          #{rand(30..37)};  # Set random hue
            #{rand(1..3)}m  # Set random brightness
                    █       # The only thing that will be visible in the terminal
                    \e[0m"} # Reset the color code to keep the blocks from
                            # interfering with each other

GW-Basic, 47 bytes (tokenised)


To get it down to 47 bytes, you'll have to strip spaces and trailing zeroes and end of file character manually.


PHP, 194 bytes

My previous answer did not animate; this one does.

<?session_register("i");$i||imagecreatetruecolor(64,64);imagesetpixel($i,rand(64)%,rand()%64,rand()%2**24);header("Content-Type: image/png");header("Location: ".basename(__FILE__));imagepng($i);

save to file, call in browser. It´s as fast as your browser can refresh.
Probably not able to set 4096 pixels in 180 seconds though.


<?                                                  # start PHP
session_register("i");                              # register image in session
$i||imagecreatetruecolor(64,64);                    # if no image exists, create one
imagesetpixel($i,rand(64)%,rand()%64,rand()%2**24); # set a random pixel to random color
header("Content-Type: image/png");                  # send HTTP header for image 
header("Location: ".basename(__FILE__));            # send HTTP header to reload
imagepng($i);                                       # send image data

SmileBASIC, 43 41 40 bytes

GPSET RND(40),RND(40),-1-RND(1<<24)EXEC.

I use -1-RND(1<<24) to generate the random color. RND(1<<24) generates a number from 0x000000 to 0xFFFFFF, and -1 - n (equivalent to bitwise NOT) will set the alpha to 0xFF (and flip the bits of the color data but that won't affect the randomness).

  • \$\begingroup\$ The console will still show over the text by default; I'd add a CLS in there to make the answer more friendly. \$\endgroup\$
    – snail_
    May 1, 2018 at 3:00
  • 1
    \$\begingroup\$ ? would also work, because it'll scroll all the text offscreen after 29 iterations. I think I could add it for 1 or 2 characters but I don't think it's necessary. \$\endgroup\$
    – 12Me21
    Feb 7, 2019 at 21:42

Racket (ISL w/ lambda + universe.rkt), 168 bytes

(define(r x)(random x))(big-bang(empty-scene 40 40)[to-draw(lambda(x)x)][on-tick(lambda(x)(place-image(square 1'solid(make-color(r 255)(r 255)(r 255)))(r 40)(r 40)x))])


(define (r x) (random x))
(big-bang (empty-scene 40 40)
  [to-draw (lambda (x) x)]
  [on-tick (lambda (x) (place-image (square 1 "solid" (make-color (r 255) (r 255) (r 255))) (r 40) (r 40) x))])

Pretty simple, just places a randomly-colored 1-pixel square at a random location from 0 to 40.

Output after ~3 minutes:

program output

Can anyone guess what book I've been reading, given my language choice?


Batch 165 156 bytes

  • \E must be replaced with escape character OR download original from pastebin
  • requires windows 10 with virtual terminal sequences enabled
  • note: code contains trailing whitespace
@mode 40,40&@Setlocal EnableDelayedExpansion&@For /l %%i in ()Do @Set/AY=!random!%%40+1,X=!random!%%40+1,c=!random!%%256+1&<nul Set/p=\E[!Y!;!X!H\E[48;5;!c!m 



Java, 401 383 373 bytes

Golfed version:

import java.awt.image.*;import java.util.*;class R{public static void main(String[]a){new javax.swing.JFrame(){int w=200;BufferedImage i=new BufferedImage(w,w,1);Random r=new Random();{setSize(w,w);show();new Thread(()->{for(;;){i.setRGB(r.nextInt(w),r.nextInt(w),r.nextInt(1<<24));repaint();}}).start();}public void paint(java.awt.Graphics g){g.drawImage(i,0,0,null);}};}}

Ungolfed version:

import java.awt.image.*;
import java.util.*;

class R {
    public static void main(String[] a) {
        new javax.swing.JFrame() {
            int w = 200;                           // a constant for width and height
            BufferedImage i = new BufferedImage(
                                        w, w,      // image width and height
                                        1);        // image type BufferedImage.TYPE_INT_RGB
            Random r = new Random();
                setSize(w, w);                     // frame big enough for image
                show();                            // make the frame visible
                new Thread(() -> {                 // create a forever running thread
                    for(;;) {
                             r.nextInt(w),         // random x position in range 0 .. w-1
                             r.nextInt(w),         // random y position in range 0 .. w-1
                             r.nextInt(1 << 24));  // random RGB value in range 0x000000 .. 0xFFFFFF
                        repaint();                 // trigger a call to the paint method
                }).start();                        // start the thread

            public void paint(java.awt.Graphics g) {
                g.drawImage(i, 0, 0, null);        // draw the whole image at x=0, y=0


enter image description here


Python, 162 bytes

Uses OpenCV library to show the RGB array. Pair of bytes can be saved if define smaller array or a square array.
Note: imshow and waitkey methods are from cv2 module; zeros and random.randint are from numpy module.

from cv2 import *
from numpy import *
while 1:

Python 3 with Pygame, 171 Bytes

import pygame as p,random as r

bash and utils, 45 bytes

Inspired (well, stolen from?) @marcosm answer, here is a quite golfed down version (from his 56 bytes down to 45, shaving the -n 1, and xarg-ing into a printf %s):

shuf -i 0-16777215|xargs printf "\e[48;5;%sm "  # \e is replaced by 1 character, Escape

Tcl/Tk, 139

Must be run in the interactive shell

gri [can .c -w 40 -he 40]
set x 0
wh 1 {.c cr o $x [set y [exp int(rand()*40)]] $x [set x $y] -f #[form %06x [exp int(rand()*255**3)]]

Unfortunately, converting expr int(rand()* into a proc makes the script have one byte more!

enter image description here

To stop, one just needs to click the ineffable "X" button.

I've reused the code of present answer on https://codegolf.stackexchange.com/a/148124/29325


PostScript, 151 bytes

realtime srand[/PageSize[640 640]>>setpagedevice
10 10 scale([){rand 16#7fffffff div}def(]){rand 64 mod}def{[[[setrgbcolor]]1 1 rectfill flushpage}loop

Needs ghostscript for flushpage; not very fast! Maybe 100 pixels/second on my machine.



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.