title: Write some Genetic Quines

text:
# Question
Title: Write some Genetic Quines
In this challenge, you'll create some programs which behave similarly to genes. When you run one, it will return one of its two "alleles" (a half of its source code), and concatenating any two alleles from your programs will result in a new, functioning program (which returns its own alleles).

As an example, say you write two programs, \\$A\\$ and \\$B\\$. These in turn each consist of two "alleles", \\$A\_0A\_1\\$ and \\$B\_0B\_1\\$. Running \\$A\\$ would return either \\$A\_0\\$ or \\$A\_1\\$ randomly, and \\$B\\$ would return \\$B\_0\\$ or \\$B\_1\\$.

Combining any two of these alleles should form a program \\$C\\$. For example, \\$A\_0B\_0\\$, when run, should return one of \\$A\_0\\$ or \\$B\_0\\$, similarly to its parents. If \\$C\\$ was instead \\$A\_1B\_0\\$, it'd return one of those two alleles instead.

One possibility if you had multiple generations, starting with three programs, could look like this:

## Rules

You must write at least two genetic quines, with each initial one having two unique alleles (the total number of unique alleles should be twice the number of initial programs). All permutations of alleles must form a functioning genetic quine.

A genetic quine takes no input when run, and returns the source code of one of its two alleles, randomly. It consists only of the code in its two alleles, concatenated. For example, if `print(xyz)` and `if 1` were two alleles, `print(xyz)if 1` and `if 1print(xyz)` should both work.

Note that standard quine rules must be followed, so the genetic quines should not read their own source code, and alleles should be non-empty.

The random choice must have a uniform probability of choosing either quine, and the quines must follow standard rules (so non-empty). You may not use the current time (directly) or some undefined behavior for randomness; a properly seeded PRNG or source of randomness should be used.

## Scoring

Your score (lowest score per language wins) will be the average byte count of all of your alleles, **plus** an amount determined by \\$\frac{b}{2^{n-1}}\\$ (making your total score \\$b+\frac{b}{2^{n-1}}\\$), where \\$b\\$ is your average byte count and \\$n\\$ is the number of genetic quines you wrote. This means that writing two initial programs with four alleles would give you a "bonus" (more like a penalty) of \\$\frac{1}{2}\\$, three would give you \\$\frac{1}{4}\\$, four would be \\$\frac{1}{8}\\$, and so on. **This is a penalty, not a multiplier: your score will never be lower than your average byte count.**

# Answer
# Haskell \+ System.Random*, score ~120 bytes.

I've built a way to make an arbitrary number of alleles which grow in length at a rate of \\$O(\log(n))\\$ So you can add as many of them as you want to the bonus to asymptotically approach 0. I would have to do a lot of math to figure out what the exact optimum number of alleles is, but I can do at least 52.

For the smallest 52:

The following is the base allele:

```
;main=randomRIO(0,1)>>=([putStr x>>print x,main]!!)where x=";main=randomRIO(0,1)>>=([putStr x>>print x,main]!!)where x="

```

To get other alleles:

* Replace all the `x`s with any letter of the alphabet.
* Optionally replace both instances of `[putStr x>>print x,main]` with `[main,putStr x>>print x]`.

You can use longer names too to get as many alleles as you want.

Try it online!

Each allele is also a quine on it's own, which is fun!

But even more fun, you can also concat as many alleles as you want together and it will output one of the given alleles randomly. Unfortunately later alleles will be less likely than earlier alleles if you do more than 2.

---

* Since it's basically impossible to import stuff properly with the allele stuff going on I take the import via command line flag.
> 15 votes

# Answer
# Lost -A, score ~~249~~ \\$66+\frac{66}{2^{1404}}\\$ = ~66

Starting with Jo King's 66 byte Lost quine:

```
:2+52*95*2+>::1?:[:[[[[@^%?>([ "
////////////////////////////////

```

There are several ways of making non-functional tweaks to this code that make it still a quine. In this answer, I'm focusing on the numeric operations. For example, you can change `52*` to `19+`,`28+`,`37+`,`46+`,`55+`,`5:+`,`64+`,`73+`,`82+`,`91+`,or `25*`. This totals 12 different possibilities.

Another set of tweaks is in the operation `95*2+`. You can swap the order of operations of the multiplication (`59*2+`) or the addition (`295*+`), or rewrite the entire expression as `85*7+` or `76*5+`. All of these things are independent of each other, so there are 3\*2\*2 = 12 ways of writing the same expression. You can also (thanks to Jo King in the comments for pointing this out), write it as `:4*7+`. Because this depends on the stack before the instruction is executed, it can't be combined with any other permuters, so only adds one more way of writing the expression, bringing the total to 13.

A third set of tweaks (also thanks to Jo King in the comments) is that the `1` can be changed to to `2`,`3`,`4`,`5`,`6`,`7`,`8`, or `9`, making 9 possibilities. Likewise, the `1?` sequence can be moved one space to the left, making a total of 9\*2=18 possibilities.

I'm sure someone more familiar with the language than me could write even more of these trivial tweaks.

The tweaks shown there are independent of each other, so you can multiply the 12 ways of writing the first expression by the 13 ways of writing the second expression and the 18 ways of writing the third expression to get 2808 unique quines. If a Lost program consists of two of these quines concatenated together, then Lost's built-in random placement of the IP will result in the program executing one of the quines at random (and thus producing its source code). Each quine, by itself, makes a valid allele, and thus combining two of them produces a genetic quine, resulting in a total of 1404 valid genetic quines.

Similarly to the Haskell answer, you can concatenate any number of alleles together rather than just two, and one of them will be chosen uniformly randomly.

As an example, one could consider program A to be:

```
:2+52*295*+>::1?:[:[[[[@^%?>([ "
////////////////////////////////
:2+25*295*+>::1?:[:[[[[@^%?>([ "
////////////////////////////////

```

Try it online!

and Program B to be:

```
:2+52*259*+>::1?:[:[[[[@^%?>([ "
////////////////////////////////
:2+25*259*+>::1?:[:[[[[@^%?>([ "
////////////////////////////////

```

Try it online!
> 14 votes

# Answer
# Python 3.8, score ~ ~~105~~ ~~104~~ ~~98~~ ~~97~~ 95

Base allele:

```
(lambda A:exec(_:="from random import*;.5>random()!=print('(lambda A:exec(_:=%r))'%_)or A(A)"))

```

The other alleles can be obtained by replacing all `A`s with lowercase and uppercase alphabets for a total of 52 alleles

Try it online!

Heavily based on the JavaScript answer

-6 thanks to @Jo King

-2 thanks to @Jakque
> 4 votes

# Answer
# Python 3, ~~81~~ base allele : 71 bytes, score ~= 71

```
a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'A'))

```

```
a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'A'))a=r";from random import*;print('a=r\"'+a[:-8]+'%r))'%choice(a[-7]+'B'))

```

Try it online!

Other alleles can be created by replacing the char `A` by (almost) any char (except simple quote `'`, double quote `"`, backslash `\`, newline, line feed, tabulation, and null char)

## Old solution : Python 3.8 (pre-release), base allele : 81 bytes, score ~= 81

## Base allele

```
exec(_:="A,a,*id=id or print('exec(_:=%r)'%choice([a,_])),_;from random import*")

```

Try it online!

Other alleles can be created by replacing the first char of the string (here `A`) by any char which can be used as variable name (except `_`)

## How it works:

I started from the quine `exec(_:="print('exec(_:=%r)'%_)")`

* Since `id` is a python built-in, it is evaluated as `True`. So `id or print(...)` won't do anything in the first allele.
* `A,a,*id= ...,_` assigns `A` to something, `a` to the string of the current allele and `id` to `[]`

When come the second allele, `id` is no evaluated as `False` and `a` store the first allele.

* `id or print(...)` will now print the quine
* `choice([a,_])` will either be `a` (the first allele) or `_` (the current allele) `'exec(_:=%r)'%choice([a,_])` equals the full code of either one of the allele
> 4 votes

# Answer
# Vyxal `D`, 9 bytes, 10 alleles

## single :

```
`1ȮḢ+"℅qṪ

```

## combined :

```
`1ȮḢ+"℅qṪ`2ȮḢ+"℅qṪ

```

Try it Online!

The digit can be replaced by any digit from 0 to 9 for a total of 10 alleles

## Explanation

```
`1ȮḢ+"℅qṪ`         # push `1ȮḢ+"℅qṪ` => [ 1ȮḢ+"℅qṪ ]
          2        # push 2 => [ 1ȮḢ+"℅qṪ , 2 ]
           Ȯ       # push the second-last item => [ 1ȮḢ+"℅qṪ , 2 , 1ȮḢ+"℅qṪ ]
            Ḣ+     # remove the first char and add  => [ 1ȮḢ+"℅qṪ , 2ȮḢ+"℅qṪ ]
              "℅   # listify and pick at random => [ 1ȮḢ+"℅qṪ ] or [ 2ȮḢ+"℅qṪ ]
                qṪ # quote and remove the last char => [ `1ȮḢ+"℅qṪ ] or [ `2ȮḢ+"℅qṪ ]
                   # implicit output

```
> 2 votes

# Answer
# Charcoal, 55 bytes per allele, 23 alleles

```
≔´θ´Ｆ´‽´⎚´Ｆ´¬´ⅈ´«´´´≔´Ｆ´θ´⁺´´´´´κ´θ´»θＦ‽⎚Ｆ¬ⅈ«´≔Ｆθ⁺´´κθ»

```

Try it online! Link is to sample program of two alleles. Any of the 22 variables `αβγδεζηλμνξπρςστυφχψω` can be used in place of `θ`. (I think it might also be possible to replace the third and sixth s with  to double the number of alleles but I haven't tested this. I think I could have also started with the Charcoal quine of the same length from Minimal distinct character quine which would give me a further set of 25 alleles, since that quine doesn't use the `ι` or `κ` variables.) Explanation: Mostly based on the Charcoal quine from Golf you a quine for great good!.

```
≔´θ´Ｆ´‽´⎚´Ｆ´¬´ⅈ´«´´´≔´Ｆ´θ´⁺´´´´´κ´θ´»θ

```

Assign the string `θＦ‽⎚Ｆ¬ⅈ«´≔Ｆθ⁺´´κθ»` (a suffix of the entire allele) to a variable.

```
Ｆ‽⎚

```

Clear the canvas 50% of the time. (This is only relevant to the second allele, since it's always clear when the first allele runs.)

```
Ｆ¬ⅈ«´≔Ｆθ⁺´´κθ»

```

If the canvas is clear, then print a , then print the variable twice, the first time prefixing `´` to each character.

Note that if multiple alleles are concatenated then each has half the chance of the previous allele of appearing except the last allele which has the same chance as the penultimate allele.
> 1 votes

# Answer
## Ruby, score 66 + 66 / (2 ^ (26\*3)) ~ 66

```
eval$a=%q[($r==false||$r=rand<0.5)&&$><<"eval$a=%q[#$a]\n"&&exit]
eval$b=%q{($r==false||$r=rand<0.5)&&$><<"eval$b=%q{#$b}\n"&&exit}

```

«Genetic diversity» comes from global variable name («a» - «z») and paired delimiters for `%q` string notation (`()`, `[]` and `{}`). Non-paired delimiters (as well as `'`) won't work since they have to be the same inside. And other `%` notations won't work due to interpolation.
> 1 votes

# Answer
# Julia 1.0, score ~86

```
(a=:(push!(ARGS, "$(0 < rand(length(ARGS):1) < print("(a=:($(a)))|>eval;"))")))|>eval;
(b=:(push!(ARGS, "$(rand(length(ARGS):1) > 0 > print("(b=:($(b)))|>eval;"))")))|>eval;

```

Try it online! (the line break is here only for readability, it should be removed)

4\*52=208 alleles, 4 for the different comparison orders and 52 for the variable name (`[a-zA-Z]`).

Ends with an error, I believe it is allowed (not so sure for quines?)

Based on the following quine, which is explained in this answer by Dennis (adapted for Julia 1.0):
`(q=:(print("(q=:($(q)))|>eval")))|>eval` Try it online!
> 1 votes

---
Tags: code-challenge, quine, source-layout
---


title: Display random colored pixels

text:
# Question
Title: Display random colored pixels
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).

# Example

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

# The winner

The shortest answer in each language wins. Have fun!

# Answer
# Minecraft 1.12 Redstone Command Blocks, ~~4,355~~ 2,872 bytes

(Size determined by saved structure block file size.)

Here is a full YouTube overview, but I'll try to outline the code below.

**Setup Routine:**

This sets up the 40x40 grid of Minecraft armor stands. Armor stands are necessary because Minecraft has *no way to substitute variables into world coordinates*. So the workaround is to *refer to the location* of these armor stand entities.

```
(impulse) summon armor_stand 2 ~ 1 {CustomName:"A"} /create named armor stand
(chain) fill -2 ~ -2 43 ~ 43 stone                  /create big stone square
(chain) fill -1 ~ -1 42 ~ 42 air                    /leave just a ring of stone
(chain) setblock -4 ~ -12 redstone_block            /kicks off next sequence

```

This named armor stand is basically our "cursor" to place all the armor stands that we will need. The redstone block in the last step "powers" nearby blocks (including our command blocks), so kicks off the next loop:

```
(repeat) execute @e[name=A] ~ ~ ~ summon armor_stand ~-1 ~ ~   /create new armor stand
(chain) tp @e[name=A] ~1 ~ ~                                   /move "cursor" one block
(chain) execute @e[name=A] ~ ~ ~ testforblock ~1 ~ ~ stone     /if at end of row,
(conditional) tp @e[name=A] ~-40 ~ ~1                          /go to start of next row
(chain) execute @e[name=A] ~ ~ ~ testforblock ~ ~ ~2 stone     /If at last row
(conditional) setblock ~6 ~ ~ air                              /stop looping
(conditional) kill @e[name=A]                                  /kill cursor

```

At this point our grid is complete:

**Random Color Selector**

The purple repeaters in the center of this picture choose a random color via the following command:

```
(repeat) execute @r[type=armor_stand,r=9] ~ ~ ~ setblock ~ ~-2 ~ redstone_block

```

That "@r\[\]" is the magic sauce, it *selects a random entity in the world that matches the given conditions*. In this case, it *finds an armor stand inside a radius of 9 blocks*, and we've set up 16 armor stands, one for each wool color. Under the selected color, it places a redstone block (which powers the two command blocks on either side).

**Random Pixel Selector**

Placing the redstone block under the selected wool color triggers two more command blocks:

```
(impulse) execute @r[type=armor_stand] ~ ~ ~ setblock ~ ~3 ~ wool X
(impulse) setblock ~ ~ ~1 air

```

This first line uses our same magic *@r* command to choose *any armor stand on the entire map* (no radius restriction, so that includes the 40x40 grid), and places a wool of the selected color above its head. The X determines the color, and ranges from 0 to 15. The second command removes the redstone block so it is ready to go again.

I have 5 purple repeater blocks, and redstone works in "ticks" 20 times a second, so I'm placing 100 pixels per second (minus some color overlaps). I've timed it, and I usually get the entire grid covered in about 3 minutes.

This was fun, I'll try to look for other challenges that might also work in Minecraft. Huge thanks to lorgon111 for his YouTube Command Block tutorial series.

**EDIT: Made some serious reductions in the size of the saved structure, now at 2,872 saved bytes**:

1. Scooted things in a bit (in all 3 dimensions) so I could reduce the overall size of the saved area.
2. Changed the different colored wools to stone, they were just decorative anyway.
3. Removed the glowstone lamp.
4. Changed all air blocks to void blocks (the red squares).

Tested by pulling the saved structure into a new world, everything still works as designed.

**EDIT 2**: Read-only Dropbox link to the NBT structure file

Walk through is in my YouTube video, but here are the steps:

1. In Minecraft 1.12, create a new creative superflat world using the "Redstone Ready" preset. Make it peaceful mode.
2. Once the world exists, copy the NBT file into a new `\structures` folder you create under the current world save.
3. Back in the game, do `/give @p structure_block`, and `/tp @p -12, 56, -22` to jump to the right spot to get started.
4. Dig a hole and place the structure block at -12, 55, -22.
5. Right-click the structure block, click the mode button to switch it to "Load".
6. Type in "random\_pixels", turn "include entities" ON, and click "Load"
7. If it finds the structure file, it will preview the outline. Right-click again and click "load" to bring the structure into the world.
8. Press the button to run the setup routine.
9. When it completes, flip the switch to run the wool randomization.
> 94 votes

# Answer
# sh + ffmpeg, 52 bytes

```
ffplay -f rawvideo -s cif -pix_fmt rgb24 /dev/random

```

Does ffmpeg count as an esolang? :D

Sadly the pix\_fmt is required, as ffmpeg defaults to yuv420p. That fails the "must have equal likelihood of every possible pixel color" requirement. Conveniently, `cif` is a shortcut for a fairly large video size that uses less space than "40x40".

Unsurprisingly, optimizing this gif with gifsicle did absolutely nothing. It's 4MiB.
> 20 votes

# Answer
# C on POSIX, ~~98~~ ~~96~~ ~~95~~ 92 bytes

-3 thanks to Tas

```
#define r rand()
f(){for(srand(time(0));printf("\e[%d;%dH\e[%d;4%dm ",r%40,r%40,r%2,r%8););}

```

This chooses between 16 colors (dark grey, red, green, blue, orange, cyan, purple, light grey, black, pink, light blue, yellow, light cyan, magenta, white) and prints them directly to the terminal.

Note that if your GPU is too slow, this may seem like it's updating the entire screen at once. It's actually going pixel by pixel, but C is fast.

Alternate solution that makes the colors more distinct:

```
f(){for(srand(time(0));printf("\e[%d;%dH\e[%d;3%dm█",rand()%40,rand()%40,rand()%2,rand()%8););}

```

Proof that it goes pixel by pixel (screenshot from alternate program):

Wow, that looks almost 3-dimensional...
> 18 votes

# Answer
# JS+HTML ~~162+32 (194)~~ 124+13 (137) bytes

Thanks to Luke and other commenters for saving me lots of bytes.

```
r=n=>n*Math.random()|0
setInterval("b=c.getContext`2d`;b.fillStyle='#'+r(2**24).toString(16);b.fillRect(r(99),r(99),1,1)",0)
```

```
<canvas id=c>
```
> 14 votes

# Answer
# MATL, 28 bytes

```
40tI3$l`3l2$r,40Yr]4$Y(t3YGT

```

Try it at **MATL Online**. I have added a half-second pause (`.5Y.`) to this version.

**Explanation**

```
40       % Push the number literal 40 to the stack
t        % Duplicate
I        % Push the number 3 to the stack
3$l      % Create a 40 x 40 x 3 matrix of 1's (40 x 40 RGB image)
`        % Do...while loop
  3l1$r  % Generate 3 random numbers (RGB)
  ,      % Do twice loop
    40Yr % Generate two integers between 1 and 40. These will be the
  ]      % row and column of the pixel to replace
  4$Y(   % Replace the pixel with the random RGB value
  t      % Make a copy of the RGB image
  3YG    % Display the image
  T      % Push a literal TRUE to create an infinite loop

```
> 12 votes

# Answer
# TI-BASIC (84+C(S)E only), ~~37~~ 35 bytes

```
:For(A,1,5!
:For(B,1,5!
:Pxl-On(A,B,randInt(10,24
:End
:End
:prgmC //"C" is the name of this program

```

Due to hardware limitations, this will eventually crash, since every time a program is nested within a program in **TI-BASIC**, 15 KB of RAM are allocated to "keep a bookmark" in the parent program. This would run fine on a "theoretical" calculator with infinite RAM, but if we want it to run indefinitely on a real calculator, we can just wrap it in a `While 1` loop for an extra **2** bytes:

```
:While 1
:...
:End

```

The TI-83 family calculators with color screens (TI 84+CE and CSE) support 15 colors. They have color codes `10` through `24`. This cycles through all the pixels in a 120 by 120 (`5!`) square and assigns each a random color.

**Result:**
> 7 votes

# Answer
# Bash + coreutils, ~~59~~  56 bytes

```
for((;;)){ printf "\e[48;5;`shuf -i 0-16777215 -n1`m ";}

```

`\e[48;5;COLORm` is the escape secuence to background color.

Each "pixel" has the chance to be in the \[0..16777215\] range every time.
> 6 votes

# Answer
# MATLAB, 56 bytes

```
x=rand(40,40,3);while imagesc(x),x(randi(4800))=rand;end

```

Output looks like the image below. One "pixel" changes at a time, and only one of the RGB-colors changes.

Why? The colors in MATLAB are represented as a 3D-matrix, one layer for R,G and B. The code above changes only one of the layers per iteration. All pixels and all layers can be changed, so if you wait a bit all colors are equally possible in all positions.

Add `pause(t)` inside the loop to pause `t` seconds between each image.

You must stop it with `Ctrl`+`C`.
> 5 votes

# Answer
## Javascript+HTML 118 + 13 (131 bytes)

```
r=_=>255*Math.random()|0;setInterval('x=c.getContext`2d`;x.fillRect(r(),r(),1,1,x.fillStyle=`rgb(${[r(),r(),r()]})`)')
```

```
<canvas id=c>
```
* This will produce evenly distributed RGB colors. You cannot use Hex colors without proper padding as numbers like `#7` is not a valid color, or `#777` and `#777777` are the same color (2x the odds)
* The canvas element is 300x150 by default, but I'm actually drawing on a 255x255 square, so there are off canvas pixels, so the effective area is 255x150.
* Works only on Google Chrome.
> 5 votes

# Answer
## Processing, 90 bytes

```
void draw(){float n=noise(millis());int i=(int)(n*9999);set(i%99,i/99,(int)(n*(-1<<24)));}

```

expanded and commented:

```
void draw(){
  float n=noise(millis());//compute PRNG value
  int i=(int)(n*9999);    //compute 99x99 pixel index
  set(i%99,i/99,          //convert index to x,y
  (int)(n*(-1<<24)));     //PRNG ARGB color = PRNG value * 0xFFFFFFFF
}

```

Ideally I could use a pixel index instead of x,y location, but Processing's `pixels[]` access requires `loadPixels()` pre and `updatePixels()` post, hence the use of `set()`. `point()` would work too, but has more chars and requires `stroke()`. The random area is actually 99x99 to save a few bytes(instead of 100x100), but that should cover 40x40 with each pixel in such an area to be replaced.

Perlin noise() is is used instead of random() to keep it more pseudo-random and a byte shorter. The value is computed once, but used twice: once for the random position, then again for the colour.

The colour is actually `ARGB`(00000000 to FFFFFFFF) (not RGB) (bonus points ? :D).
> 4 votes

# Answer
# Excel VBA, ~~131~~ ~~102~~ 85 Bytes

Anonymous VBE immediate window function that uses a helper function (see below) to output an array of randomly colored cells to the range `A1:AN40` of the activesheet object.

*Note: This solution is restricted to 32-Bit installs of MS Excel (and therefore of Office as a whole) as `8^8` will not compile on 64-Bit versions of VBA*

```
Randomize:Cells.RowHeight=48:For Each c In[A1:AN40]:c.Interior.Color=(8^8-1)*Rnd:Next

```

## Sample Output

## Previous Version

```
Randomize:Cells.ColumnWidth=2:For Each c In Range("A1:AN40"):c.Interior.Color=RGB(n,n,n):Next

```

## Helper Function

Outputs a random int in the range \[0,255\]

```
Function n
n=Int(255*Rnd)
End Function

```
> 4 votes

# Answer
# x86 machine language (real mode) for IBM PC, ~~20~~ 19 bytes

```
 0:       b8 12 00                mov    $0x12,%ax
 3:       31 db                   xor    %bx,%bx
 5:       cd 10                   int    $0x10
 7:       0f c7 f0                rdrand %ax
 a:       88 e1                   mov    %ah,%cl
 c:       0f c7 f2                rdrand %dx
 f:       b4 0c                   mov    $0xc,%ah
11:       eb f2                   jmp    0x5

```

This requires a processor with the `rdrand` instruction and a VGA adapter (real or emulated). The above can be copied into a boot block or MS-DOS \*.COM file.

To try this out, compile the following and save the output to a file like `floppy.img` and boot the image on a virtual machine.

```
#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main(){
  char buffer[ 1440*1024 ];
  memcpy( buffer, "\xb8\x12\x00\x31\xdb\xcd\x10\x0f\xc7\xf0\x88\xe1\x0f\xc7\xf2\xb4\x0c\xeb\xf2", 20 );
  memcpy( buffer + 510, "\x55\xaa", 2 );
  write( 1, buffer, sizeof buffer );
}

```
> 4 votes

# Answer
## C++ on Windows, 125 bytes

```
#include<Windows.h>
#include<ctime>
#define r rand()%256
int main(){for(srand(time(0));;)SetPixel(GetDC(0),r,r,RGB(r,r,r));}

```

Newlines necessary and included in byte count.

Loops forever, randomly picks a position between 0 and 255 (inclusive) for row and column values, assigns random R,G,B values between 0-255 (inclusive)
> 3 votes

# Answer
# C#, ~~369~~ ~~288~~ 287 bytes

```
namespace System.Drawing{class P{static void Main(){var g=Graphics.FromHwnd((IntPtr)0);var w=Windows.Forms.Screen.GetBounds(Point.Empty);for(var r=new Random();;)g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256),r.Next(256),r.Next(256))),r.Next(w.Width),r.Next(w.Height),1,1);}}}

```

*Saved 88 bytes thanks to @CodyGray.*

A full program that get's the handle to the screen and it's size and then starts randomly drawing pixels on it. Note that this might grind your graphics card to a halt when ran. Also if the screen or any control decides to repaint at any time the pixels will be lost and have to be redrawn.

Note: When running keep focus on the window as to kill it you have to either Alt+F4 or press the close button and doing so when you can't see the screen is a bit hard.

I couldn't record this working, with ScreenToGif, as that kept forcing a repaint so the pixels would get removed. However, here is a screenshot of it running after about 10-15 seconds, any longer and I think I may have ground my PC to a halt! The gap in the top right corner is where the screen forced a repaint just as I took the screenshot.

Full/Formatted version:

```
namespace System.Drawing
{
    class P
    {
        static void Main()
        {
            var g = Graphics.FromHdc((IntPtr)0);
            var w = Windows.Forms.Screen.GetBounds(Point.Empty);

            for (var r = new Random();;)
                g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256), r.Next(256), r.Next(256))),
                                r.Next(w.Width), r.Next(w.Height), 1, 1);
        }
    }
}

```

---

A version for ~~308~~ ~~227~~ 226 bytes that only draws on the region 0-40:

```
namespace System.Drawing{class P{static void Main(){var g=Graphics.FromHdc((IntPtr)0);for(var r=new Random();;)g.FillRectangle(new SolidBrush(Color.FromArgb(r.Next(256),r.Next(256),r.Next(256))),r.Next(40),r.Next(40),1,1);}}}

```

Example output for this one:

---
> 3 votes

# Answer
# C# Console, 233 220 ~~189~~ 188 bytes

```
namespace System{using static Console;class P{static void Main(){for(var r=new Random();;){BackgroundColor=(ConsoleColor)r.Next(16);SetCursorPosition(r.Next(40),r.Next(40));Write(" ");}}}}

```

Uses "all" (windows) 16 console colors.

Thanks for the "feature" to be able to alias classes in C# via the `using` directive.

**Edit #1**

* Removed some spaces.
* Removed zeros from Random.Next()
* Went to `namespace system{...}`

**Edit #2**

* Minimum size of grid is 40x40
* One byte by declaring Random in for loop header
* Removed `public` from Main method

**Edit #3**

Turns out `using C=Console;` is **not** the best there is. `using static Console` is much like the VB.Net way to "Import" classes

I give up: TheLethalCoder made this happen

---

Original code for adapting window size at 207 bytes:

```
namespace System{using static Console;class P{static void Main(){for(var r=new Random();;){BackgroundColor=(ConsoleColor)r.Next(16);SetCursorPosition(r.Next(WindowWidth),r.Next(WindowHeight));Write(" ");}}}}

```

Original Image:
> 3 votes

# Answer
# 6502 Assembly, 92 bytes

```
loo: lda $fe
sta $00
lda $fe
and #$3
clc
adc #$2
sta $01
lda $fe
ldy #$0
sta ($00),y
jmp loo

```

Output:

Explanation:

```
loop: lda $fe       ; accumulator = random
      sta $00       ; store accumulator
      lda $fe       ; accumulator = random
      and #$3       ; accumulator &= 3
      clc           ; clear carry
      adc #$2       ; accumulator += 2
      sta $01       ; store accumulator
      lda $fe       ; accumulator = random
      ldy #$0       ; register Y = 0
      sta ($00),y   ; store register Y
      jmp loop      ; loop

```
> 3 votes

# Answer
# 6502 Assembly, 582 bytes

Whew, this was fun. Does more or less the same thing as my Applesoft BASIC solution.

```
start:
lda #15
sta $0
sta $1
loo:
lda $fe
and #3
cmp #0
beq g_l
cmp #1
beq g_r
cmp #2
beq g_d
dec $1
d_w:
lda $1
and #$1f
asl
tax
lda ypo,x
sta $2
inx
lda ypo,x
sta $3
lda $0
and #$1f
tay
lda ($2),y
tax
inx
txa
sta ($2),y
jmp loo
g_d:
inc $1
jmp d_w
g_l:
dec $0
jmp d_w
g_r:
inc $0
jmp d_w
ypo:
dcb $00,$02,$20,$02,$40,$02,$60,$02
dcb $80,$02,$a0,$02,$c0,$02,$e0,$02
dcb $00,$03,$20,$03,$40,$03,$60,$03
dcb $80,$03,$a0,$03,$c0,$03,$e0,$03
dcb $00,$04,$20,$04,$40,$04,$60,$04
dcb $80,$04,$a0,$04,$c0,$04,$e0,$04
dcb $00,$05,$20,$05,$40,$05,$60,$05
dcb $80,$05,$a0,$05,$c0,$05,$e0,$05

```
> 3 votes

# Answer
# Python 3.6 + Tkinter, 281 bytes

```
from tkinter import*
from random import*
from threading import*
a=randrange
x=40
d={"width":x,"height":x}
w=Tk()
c=Canvas(w,**d)
c.pack()
i=PhotoImage(**d)
c.create_image((20,20),image=i)
def r():
 while 1:i.put(f"{a(0,0xffffff):0>6f}",(a(0,x),a(0,x)))
Thread(r).start()
mainloop()

```
> 2 votes

# Answer
# JavaScript using Canvas 340 316 324 bytes

```
function r(t,e){return Math.floor(e*Math.random()+t)}function f(){x.fillStyle="rgba("+r(1,255)+","+r(1,255)+","+r(1,255)+", 1)",x.fillRect(r(0,40),r(0,40),1,1)}c=document.createElement("canvas"),c.width=40,c.height=40,x=c.getContext("2d"),document.getElementsByTagName("body")[0].appendChild(c),c.interval=setInterval(f,1);
```

full version
> 2 votes

# Answer
# HTML+SVG+PHP, 245 Bytes

```
<?$u=$_GET;$u[rand()%40][rand()%40]=sprintf("%06x",rand()%16777216);echo'<meta http-equiv="refresh" content="0.1; url=?'.http_build_query($u).'" /><svg>';foreach($u as$x=>$a)foreach($a as$y=>$c)echo"<rect x=$x y=$y width=1 height=1 fill=#$c />";

```

Expanded

```
$u=$_GET; # Get the Url
$u[rand()%40][rand()%40]=sprintf("%06x",rand()%16777216); # Set One Value in a 2 D Array
echo'<meta http-equiv="refresh" content="0.1; url=?'.http_build_query($u).'" /><svg>'; # refresh the site after 0.1 second follow the new Get parameter
foreach($u as$x=>$a) #loop through x Coordinates as Key
  foreach($a as$y=>$c) #loop through y Coordinates as Key value is the color
    echo"<rect x=$x y=$y width=1 height=1 fill=#$c />"; #print the rects for the SVG

```

Example for Output without meta tag and in a greater version

```
<svg viewBox="0 0 40 40" width=400 height=400><rect x=11 y=39 width=1 height=1 fill=#1b372b /><rect x=11 y=7 width=1 height=1 fill=#2c55a7 /><rect x=11 y=31 width=1 height=1 fill=#97ef86 /><rect x=11 y=26 width=1 height=1 fill=#94aa0a /><rect x=11 y=4 width=1 height=1 fill=#f8bf89 /><rect x=11 y=6 width=1 height=1 fill=#266342 /><rect x=11 y=29 width=1 height=1 fill=#369d80 /><rect x=11 y=20 width=1 height=1 fill=#ccfab8 /><rect x=11 y=12 width=1 height=1 fill=#ac0273 /><rect x=13 y=25 width=1 height=1 fill=#0d95e9 /><rect x=13 y=0 width=1 height=1 fill=#d2a4cb /><rect x=13 y=37 width=1 height=1 fill=#503abe /><rect x=13 y=35 width=1 height=1 fill=#4e60ae /><rect x=13 y=30 width=1 height=1 fill=#3cdd5e /><rect x=13 y=12 width=1 height=1 fill=#60464c /><rect x=13 y=17 width=1 height=1 fill=#a3b234 /><rect x=13 y=3 width=1 height=1 fill=#48e937 /><rect x=13 y=20 width=1 height=1 fill=#58bb78 /><rect x=13 y=4 width=1 height=1 fill=#5c61e6 /><rect x=13 y=10 width=1 height=1 fill=#758613 /><rect x=13 y=21 width=1 height=1 fill=#9b3a09 /><rect x=13 y=28 width=1 height=1 fill=#6c6b3b /><rect x=13 y=32 width=1 height=1 fill=#9b3a0f /><rect x=13 y=14 width=1 height=1 fill=#0c9bcc /><rect x=38 y=34 width=1 height=1 fill=#a3a65d /><rect x=38 y=23 width=1 height=1 fill=#c4441a /><rect x=38 y=25 width=1 height=1 fill=#cec692 /><rect x=38 y=39 width=1 height=1 fill=#535401 /><rect x=38 y=30 width=1 height=1 fill=#21371a /><rect x=38 y=26 width=1 height=1 fill=#7560a4 /><rect x=38 y=33 width=1 height=1 fill=#f31f34 /><rect x=38 y=9 width=1 height=1 fill=#3fce3f /><rect x=38 y=13 width=1 height=1 fill=#78cab8 /><rect x=3 y=39 width=1 height=1 fill=#c6cf06 /><rect x=3 y=26 width=1 height=1 fill=#d7fc94 /><rect x=3 y=31 width=1 height=1 fill=#048791 /><rect x=3 y=19 width=1 height=1 fill=#140371 /><rect x=3 y=12 width=1 height=1 fill=#6e7e7a /><rect x=3 y=21 width=1 height=1 fill=#f917da /><rect x=3 y=36 width=1 height=1 fill=#00d5d7 /><rect x=3 y=24 width=1 height=1 fill=#00f119 /><rect x=34 y=15 width=1 height=1 fill=#e39bd7 /><rect x=34 y=1 width=1 height=1 fill=#c1c1b8 /><rect x=34 y=36 width=1 height=1 fill=#0d15d5 /><rect x=34 y=29 width=1 height=1 fill=#d15f57 /><rect x=34 y=11 width=1 height=1 fill=#6f73b9 /><rect x=34 y=33 width=1 height=1 fill=#93ce78 /><rect x=34 y=16 width=1 height=1 fill=#ddd7bd /><rect x=34 y=14 width=1 height=1 fill=#73caa6 /><rect x=34 y=28 width=1 height=1 fill=#972d89 /><rect x=34 y=31 width=1 height=1 fill=#27e401 /><rect x=34 y=10 width=1 height=1 fill=#559d6d /><rect x=34 y=22 width=1 height=1 fill=#170bc2 /><rect x=30 y=13 width=1 height=1 fill=#a9ac0d /><rect x=30 y=4 width=1 height=1 fill=#3d9530 /><rect x=30 y=10 width=1 height=1 fill=#67b434 /><rect x=30 y=15 width=1 height=1 fill=#54930a /><rect x=30 y=11 width=1 height=1 fill=#8ce15b /><rect x=30 y=7 width=1 height=1 fill=#ddf53d /><rect x=30 y=32 width=1 height=1 fill=#04de14 /><rect x=30 y=19 width=1 height=1 fill=#f52098 /><rect x=30 y=22 width=1 height=1 fill=#dc7d70 /><rect x=30 y=0 width=1 height=1 fill=#d458c3 /><rect x=30 y=30 width=1 height=1 fill=#1f8895 /><rect x=30 y=36 width=1 height=1 fill=#b3d891 /><rect x=30 y=29 width=1 height=1 fill=#0f9810 /><rect x=30 y=5 width=1 height=1 fill=#b4ce36 /><rect x=30 y=33 width=1 height=1 fill=#a837ba /><rect x=30 y=23 width=1 height=1 fill=#02beb3 /><rect x=30 y=24 width=1 height=1 fill=#2a75da /><rect x=37 y=2 width=1 height=1 fill=#7b3aa3 /><rect x=37 y=26 width=1 height=1 fill=#0e9fb2 /><rect x=37 y=32 width=1 height=1 fill=#afb3a1 /><rect x=37 y=24 width=1 height=1 fill=#b421d6 /><rect x=37 y=16 width=1 height=1 fill=#39e872 /><rect x=37 y=38 width=1 height=1 fill=#552970 /><rect x=37 y=11 width=1 height=1 fill=#2a0b2a /><rect x=37 y=18 width=1 height=1 fill=#1fe310 /><rect x=37 y=36 width=1 height=1 fill=#a80fe3 /><rect x=37 y=6 width=1 height=1 fill=#141100 /><rect x=26 y=13 width=1 height=1 fill=#5d521d /><rect x=26 y=11 width=1 height=1 fill=#d7227e /><rect x=26 y=1 width=1 height=1 fill=#8dae67 /><rect x=26 y=19 width=1 height=1 fill=#acfd2c /><rect x=26 y=2 width=1 height=1 fill=#307dd5 /><rect x=26 y=35 width=1 height=1 fill=#76b559 /><rect x=26 y=4 width=1 height=1 fill=#e6a551 /><rect x=12 y=34 width=1 height=1 fill=#266a0a /><rect x=12 y=16 width=1 height=1 fill=#8bcf44 /><rect x=12 y=13 width=1 height=1 fill=#00caac /><rect x=12 y=3 width=1 height=1 fill=#bb7aa5 /><rect x=12 y=37 width=1 height=1 fill=#3b0559 /><rect x=12 y=27 width=1 height=1 fill=#e82087 /><rect x=12 y=8 width=1 height=1 fill=#b65157 /><rect x=19 y=20 width=1 height=1 fill=#556336 /><rect x=19 y=33 width=1 height=1 fill=#81bca0 /><rect x=19 y=34 width=1 height=1 fill=#65478a /><rect x=19 y=35 width=1 height=1 fill=#256956 /><rect x=19 y=10 width=1 height=1 fill=#c49f9c /><rect x=19 y=12 width=1 height=1 fill=#99bd3d /><rect x=19 y=13 width=1 height=1 fill=#dae45d /><rect x=19 y=36 width=1 height=1 fill=#de28e2 /><rect x=19 y=30 width=1 height=1 fill=#f26ff1 /><rect x=4 y=23 width=1 height=1 fill=#3a31dc /><rect x=4 y=4 width=1 height=1 fill=#d480e7 /><rect x=4 y=24 width=1 height=1 fill=#a304c6 /><rect x=4 y=28 width=1 height=1 fill=#775aeb /><rect x=4 y=16 width=1 height=1 fill=#d942d1 /><rect x=4 y=8 width=1 height=1 fill=#ad6c7e /><rect x=4 y=3 width=1 height=1 fill=#8ef507 /><rect x=4 y=9 width=1 height=1 fill=#c59549 /><rect x=4 y=7 width=1 height=1 fill=#f757fb /><rect x=4 y=35 width=1 height=1 fill=#2db5de /><rect x=20 y=22 width=1 height=1 fill=#340f7b /><rect x=20 y=2 width=1 height=1 fill=#ae6b7c /><rect x=20 y=20 width=1 height=1 fill=#120232 /><rect x=20 y=1 width=1 height=1 fill=#bb534c /><rect x=20 y=11 width=1 height=1 fill=#a736a1 /><rect x=20 y=38 width=1 height=1 fill=#63646f /><rect x=20 y=8 width=1 height=1 fill=#8e2095 /><rect x=20 y=27 width=1 height=1 fill=#2ae2c6 /><rect x=32 y=20 width=1 height=1 fill=#56dc7a /><rect x=32 y=34 width=1 height=1 fill=#ec16ca /><rect x=32 y=19 width=1 height=1 fill=#e2ce80 /><rect x=32 y=21 width=1 height=1 fill=#5c7638 /><rect x=32 y=0 width=1 height=1 fill=#35647c /><rect x=32 y=33 width=1 height=1 fill=#9e174a /><rect x=32 y=5 width=1 height=1 fill=#8217b4 /><rect x=32 y=30 width=1 height=1 fill=#b3e018 /><rect x=32 y=36 width=1 height=1 fill=#90ea3d /><rect x=22 y=29 width=1 height=1 fill=#9d975f /><rect x=22 y=12 width=1 height=1 fill=#b50680 /><rect x=22 y=31 width=1 height=1 fill=#9cd270 /><rect x=22 y=16 width=1 height=1 fill=#05a7f7 /><rect x=22 y=20 width=1 height=1 fill=#f6c4d5 /><rect x=22 y=21 width=1 height=1 fill=#9b0dd8 /><rect x=22 y=22 width=1 height=1 fill=#bc1c9e /><rect x=22 y=26 width=1 height=1 fill=#22b4c3 /><rect x=22 y=36 width=1 height=1 fill=#f54b7b /><rect x=22 y=19 width=1 height=1 fill=#7d3be4 /><rect x=22 y=6 width=1 height=1 fill=#ff9c6f /><rect x=22 y=34 width=1 height=1 fill=#cce01c /><rect x=22 y=30 width=1 height=1 fill=#7c4fd0 /><rect x=22 y=33 width=1 height=1 fill=#c2ef4e /><rect x=25 y=3 width=1 height=1 fill=#35c580 /><rect x=25 y=31 width=1 height=1 fill=#172b52 /><rect x=25 y=39 width=1 height=1 fill=#5e724d /><rect x=25 y=10 width=1 height=1 fill=#f50c4a /><rect x=25 y=4 width=1 height=1 fill=#012808 /><rect x=25 y=33 width=1 height=1 fill=#3a0dc3 /><rect x=25 y=12 width=1 height=1 fill=#2f254a /><rect x=25 y=30 width=1 height=1 fill=#19ff2c /><rect x=25 y=38 width=1 height=1 fill=#4a3112 /><rect x=0 y=1 width=1 height=1 fill=#886f4f /><rect x=0 y=35 width=1 height=1 fill=#0bb010 /><rect x=0 y=0 width=1 height=1 fill=#a7f77e /><rect x=0 y=27 width=1 height=1 fill=#1b38da /><rect x=0 y=39 width=1 height=1 fill=#3788ae /><rect x=0 y=13 width=1 height=1 fill=#af5149 /><rect x=0 y=32 width=1 height=1 fill=#dcb445 /><rect x=0 y=20 width=1 height=1 fill=#36a218 /><rect x=0 y=2 width=1 height=1 fill=#aacbb8 /><rect x=0 y=14 width=1 height=1 fill=#fb17e3 /><rect x=17 y=8 width=1 height=1 fill=#cb2be8 /><rect x=17 y=11 width=1 height=1 fill=#dd80b1 /><rect x=17 y=35 width=1 height=1 fill=#a269aa /><rect x=17 y=6 width=1 height=1 fill=#9faf64 /><rect x=17 y=9 width=1 height=1 fill=#762811 /><rect x=17 y=23 width=1 height=1 fill=#94fa57 /><rect x=17 y=26 width=1 height=1 fill=#9bacc3 /><rect x=17 y=1 width=1 height=1 fill=#93c849 /><rect x=17 y=4 width=1 height=1 fill=#4a9fd4 /><rect x=17 y=22 width=1 height=1 fill=#1fc5f3 /><rect x=17 y=37 width=1 height=1 fill=#76d6a3 /><rect x=17 y=5 width=1 height=1 fill=#a13389 /><rect x=9 y=38 width=1 height=1 fill=#064ba3 /><rect x=9 y=23 width=1 height=1 fill=#cc83ad /><rect x=9 y=25 width=1 height=1 fill=#1de7e8 /><rect x=9 y=3 width=1 height=1 fill=#834afe /><rect x=9 y=9 width=1 height=1 fill=#15a0fb /><rect x=9 y=27 width=1 height=1 fill=#4d54dc /><rect x=9 y=21 width=1 height=1 fill=#2bf614 /><rect x=9 y=28 width=1 height=1 fill=#8080b7 /><rect x=9 y=39 width=1 height=1 fill=#d76a3b /><rect x=9 y=33 width=1 height=1 fill=#f8da2c /><rect x=9 y=26 width=1 height=1 fill=#5884ae /><rect x=7 y=39 width=1 height=1 fill=#a0264b /><rect x=7 y=15 width=1 height=1 fill=#bd87c7 /><rect x=7 y=18 width=1 height=1 fill=#4d4878 /><rect x=7 y=35 width=1 height=1 fill=#1dcc8c /><rect x=7 y=38 width=1 height=1 fill=#76497f /><rect x=7 y=1 width=1 height=1 fill=#87b1ae /><rect x=35 y=24 width=1 height=1 fill=#5d947e /><rect x=35 y=17 width=1 height=1 fill=#eabbdc /><rect x=35 y=19 width=1 height=1 fill=#01c75b /><rect x=35 y=36 width=1 height=1 fill=#06b0dd /><rect x=35 y=21 width=1 height=1 fill=#0fbba8 /><rect x=35 y=1 width=1 height=1 fill=#480be1 /><rect x=35 y=11 width=1 height=1 fill=#3f8ef6 /><rect x=35 y=30 width=1 height=1 fill=#7691d0 /><rect x=35 y=13 width=1 height=1 fill=#c9a286 /><rect x=27 y=12 width=1 height=1 fill=#08083e /><rect x=27 y=25 width=1 height=1 fill=#95d3b4 /><rect x=27 y=30 width=1 height=1 fill=#584c1b /><rect x=27 y=9 width=1 height=1 fill=#c01082 /><rect x=27 y=3 width=1 height=1 fill=#3bf653 /><rect x=27 y=33 width=1 height=1 fill=#c06f23 /><rect x=27 y=38 width=1 height=1 fill=#184c3e /><rect x=27 y=0 width=1 height=1 fill=#725d4c /><rect x=27 y=36 width=1 height=1 fill=#e7a71b /><rect x=27 y=16 width=1 height=1 fill=#43c039 /><rect x=23 y=30 width=1 height=1 fill=#947161 /><rect x=23 y=37 width=1 height=1 fill=#e8a8e5 /><rect x=23 y=12 width=1 height=1 fill=#bd9976 /><rect x=23 y=6 width=1 height=1 fill=#15085d /><rect x=23 y=31 width=1 height=1 fill=#102c95 /><rect x=23 y=24 width=1 height=1 fill=#173bc2 /><rect x=23 y=2 width=1 height=1 fill=#bac13c /><rect x=23 y=36 width=1 height=1 fill=#eb5a88 /><rect x=23 y=22 width=1 height=1 fill=#5ddc38 /><rect x=28 y=19 width=1 height=1 fill=#1ea833 /><rect x=28 y=38 width=1 height=1 fill=#dc6f6b /><rect x=28 y=2 width=1 height=1 fill=#d9fd8a /><rect x=28 y=15 width=1 height=1 fill=#eb213e /><rect x=28 y=22 width=1 height=1 fill=#b23956 /><rect x=28 y=16 width=1 height=1 fill=#875b0a /><rect x=28 y=14 width=1 height=1 fill=#ba6172 /><rect x=28 y=18 width=1 height=1 fill=#b9779a /><rect x=39 y=26 width=1 height=1 fill=#df5e52 /><rect x=39 y=4 width=1 height=1 fill=#aabb4f /><rect x=39 y=2 width=1 height=1 fill=#7ce85c /><rect x=39 y=16 width=1 height=1 fill=#1f70a8 /><rect x=39 y=15 width=1 height=1 fill=#55e398 /><rect x=39 y=29 width=1 height=1 fill=#955213 /><rect x=39 y=33 width=1 height=1 fill=#976c99 /><rect x=39 y=34 width=1 height=1 fill=#a23109 /><rect x=39 y=25 width=1 height=1 fill=#36aeae /><rect x=39 y=9 width=1 height=1 fill=#28a600 /><rect x=39 y=17 width=1 height=1 fill=#771e5b /><rect x=39 y=30 width=1 height=1 fill=#9980b1 /><rect x=31 y=14 width=1 height=1 fill=#8ffea6 /><rect x=31 y=13 width=1 height=1 fill=#d35c5c /><rect x=31 y=39 width=1 height=1 fill=#407beb /><rect x=31 y=10 width=1 height=1 fill=#45ba53 /><rect x=31 y=2 width=1 height=1 fill=#842997 /><rect x=31 y=20 width=1 height=1 fill=#ca47b0 /><rect x=31 y=37 width=1 height=1 fill=#ed098e /><rect x=31 y=5 width=1 height=1 fill=#041b67 /><rect x=31 y=22 width=1 height=1 fill=#4aaaa6 /><rect x=31 y=31 width=1 height=1 fill=#40ccbd /><rect x=31 y=27 width=1 height=1 fill=#6325ca /><rect x=33 y=18 width=1 height=1 fill=#cfbbbc /><rect x=33 y=34 width=1 height=1 fill=#b3f6b8 /><rect x=33 y=26 width=1 height=1 fill=#ef3b82 /><rect x=33 y=16 width=1 height=1 fill=#c7df5b /><rect x=33 y=39 width=1 height=1 fill=#5ad5ba /><rect x=33 y=12 width=1 height=1 fill=#9361fd /><rect x=33 y=35 width=1 height=1 fill=#1f4795 /><rect x=33 y=3 width=1 height=1 fill=#86a80c /><rect x=33 y=17 width=1 height=1 fill=#582008 /><rect x=33 y=9 width=1 height=1 fill=#686941 /><rect x=33 y=36 width=1 height=1 fill=#76ada4 /><rect x=33 y=21 width=1 height=1 fill=#511f50 /><rect x=33 y=14 width=1 height=1 fill=#64aaf7 /><rect x=8 y=28 width=1 height=1 fill=#3de9b7 /><rect x=8 y=24 width=1 height=1 fill=#5c8451 /><rect x=8 y=31 width=1 height=1 fill=#e75b30 /><rect x=8 y=38 width=1 height=1 fill=#4ee9d0 /><rect x=8 y=29 width=1 height=1 fill=#544381 /><rect x=8 y=16 width=1 height=1 fill=#12332f /><rect x=8 y=0 width=1 height=1 fill=#9e775f /><rect x=8 y=34 width=1 height=1 fill=#02224e /><rect x=8 y=1 width=1 height=1 fill=#b299f4 /><rect x=8 y=10 width=1 height=1 fill=#b2bd80 /><rect x=8 y=20 width=1 height=1 fill=#054876 /><rect x=8 y=27 width=1 height=1 fill=#ab273a /><rect x=2 y=30 width=1 height=1 fill=#1bd5f4 /><rect x=2 y=10 width=1 height=1 fill=#b00e99 /><rect x=2 y=9 width=1 height=1 fill=#bf18b0 /><rect x=2 y=8 width=1 height=1 fill=#9aa92b /><rect x=2 y=16 width=1 height=1 fill=#aa7e3d /><rect x=2 y=1 width=1 height=1 fill=#c383ea /><rect x=2 y=24 width=1 height=1 fill=#63ab54 /><rect x=2 y=19 width=1 height=1 fill=#086cac /><rect x=2 y=0 width=1 height=1 fill=#4510cc /><rect x=2 y=6 width=1 height=1 fill=#7b529c /><rect x=6 y=27 width=1 height=1 fill=#fcc946 /><rect x=6 y=20 width=1 height=1 fill=#0a7324 /><rect x=6 y=26 width=1 height=1 fill=#d93cc2 /><rect x=6 y=14 width=1 height=1 fill=#c8d410 /><rect x=6 y=33 width=1 height=1 fill=#0e5b22 /><rect x=6 y=1 width=1 height=1 fill=#e2accf /><rect x=6 y=2 width=1 height=1 fill=#06064a /><rect x=6 y=39 width=1 height=1 fill=#fae1de /><rect x=6 y=30 width=1 height=1 fill=#db50d3 /><rect x=6 y=15 width=1 height=1 fill=#59b1c5 /><rect x=6 y=16 width=1 height=1 fill=#a0178a /><rect x=16 y=29 width=1 height=1 fill=#1eb287 /><rect x=16 y=31 width=1 height=1 fill=#5fa9b0 /><rect x=16 y=36 width=1 height=1 fill=#918835 /><rect x=16 y=2 width=1 height=1 fill=#d46404 /><rect x=16 y=1 width=1 height=1 fill=#31808e /><rect x=16 y=15 width=1 height=1 fill=#22d652 /><rect x=10 y=25 width=1 height=1 fill=#94f771 /><rect x=10 y=14 width=1 height=1 fill=#e3a90a /><rect x=10 y=4 width=1 height=1 fill=#7fbdb3 /><rect x=10 y=32 width=1 height=1 fill=#d71f68 /><rect x=10 y=10 width=1 height=1 fill=#f3dcd7 /><rect x=10 y=27 width=1 height=1 fill=#cadd64 /><rect x=10 y=31 width=1 height=1 fill=#3c38c0 /><rect x=10 y=34 width=1 height=1 fill=#542641 /><rect x=10 y=19 width=1 height=1 fill=#e17ef2 /><rect x=10 y=24 width=1 height=1 fill=#676729 /><rect x=10 y=11 width=1 height=1 fill=#619f8e /><rect x=10 y=0 width=1 height=1 fill=#1576eb /><rect x=10 y=16 width=1 height=1 fill=#52854c /><rect x=36 y=2 width=1 height=1 fill=#fe133c /><rect x=36 y=31 width=1 height=1 fill=#b67ea7 /><rect x=36 y=7 width=1 height=1 fill=#92babc /><rect x=36 y=16 width=1 height=1 fill=#fc24a0 /><rect x=36 y=26 width=1 height=1 fill=#a80f75 /><rect x=36 y=15 width=1 height=1 fill=#5ddb90 /><rect x=18 y=13 width=1 height=1 fill=#64180c /><rect x=18 y=9 width=1 height=1 fill=#d67c04 /><rect x=18 y=18 width=1 height=1 fill=#3e0988 /><rect x=18 y=4 width=1 height=1 fill=#072b32 /><rect x=18 y=34 width=1 height=1 fill=#723cab /><rect x=18 y=14 width=1 height=1 fill=#560f7d /><rect x=18 y=29 width=1 height=1 fill=#4a7dd0 /><rect x=18 y=30 width=1 height=1 fill=#db0cfc /><rect x=18 y=16 width=1 height=1 fill=#f79bbf /><rect x=14 y=18 width=1 height=1 fill=#e45cec /><rect x=14 y=4 width=1 height=1 fill=#05b63c /><rect x=14 y=38 width=1 height=1 fill=#ee0251 /><rect x=14 y=14 width=1 height=1 fill=#12fb9f /><rect x=14 y=17 width=1 height=1 fill=#f8fbc9 /><rect x=14 y=22 width=1 height=1 fill=#58e112 /><rect x=14 y=1 width=1 height=1 fill=#a5bc5c /><rect x=14 y=10 width=1 height=1 fill=#3c6002 /><rect x=14 y=5 width=1 height=1 fill=#556f7a /><rect x=14 y=36 width=1 height=1 fill=#ccfaa9 /><rect x=14 y=15 width=1 height=1 fill=#2a8597 /><rect x=1 y=28 width=1 height=1 fill=#899272 /><rect x=1 y=29 width=1 height=1 fill=#be4da2 /><rect x=1 y=6 width=1 height=1 fill=#cbe1a5 /><rect x=1 y=1 width=1 height=1 fill=#8aebd4 /><rect x=1 y=31 width=1 height=1 fill=#547b9e /><rect x=1 y=10 width=1 height=1 fill=#ba7996 /><rect x=1 y=34 width=1 height=1 fill=#e29661 /><rect x=1 y=0 width=1 height=1 fill=#899d3f /><rect x=1 y=4 width=1 height=1 fill=#6993f0 /><rect x=1 y=13 width=1 height=1 fill=#119a7c /><rect x=1 y=15 width=1 height=1 fill=#e7c61c /><rect x=1 y=17 width=1 height=1 fill=#6e8770 /><rect x=1 y=36 width=1 height=1 fill=#cdda71 /><rect x=5 y=8 width=1 height=1 fill=#318f52 /><rect x=5 y=34 width=1 height=1 fill=#763499 /><rect x=5 y=37 width=1 height=1 fill=#5d0d72 /><rect x=5 y=0 width=1 height=1 fill=#97c9e7 /><rect x=5 y=12 width=1 height=1 fill=#babcca /><rect x=5 y=20 width=1 height=1 fill=#37d5cb /><rect x=5 y=31 width=1 height=1 fill=#642296 /><rect x=5 y=24 width=1 height=1 fill=#a6688c /><rect x=5 y=1 width=1 height=1 fill=#697956 /><rect x=29 y=32 width=1 height=1 fill=#b53b61 /><rect x=29 y=7 width=1 height=1 fill=#d131a3 /><rect x=29 y=18 width=1 height=1 fill=#0e082e /><rect x=29 y=17 width=1 height=1 fill=#8ca3dd /><rect x=29 y=11 width=1 height=1 fill=#376e46 /><rect x=29 y=20 width=1 height=1 fill=#11e2cf /><rect x=29 y=37 width=1 height=1 fill=#24b8de /><rect x=24 y=10 width=1 height=1 fill=#a906da /><rect x=24 y=36 width=1 height=1 fill=#ae0516 /><rect x=24 y=8 width=1 height=1 fill=#e0b9b1 /><rect x=24 y=27 width=1 height=1 fill=#29b27b /><rect x=24 y=33 width=1 height=1 fill=#78ea3e /><rect x=24 y=7 width=1 height=1 fill=#e5147e /><rect x=24 y=11 width=1 height=1 fill=#ce7084 /><rect x=24 y=23 width=1 height=1 fill=#78f645 /><rect x=24 y=25 width=1 height=1 fill=#a01f02 /><rect x=24 y=4 width=1 height=1 fill=#e4340c /><rect x=24 y=16 width=1 height=1 fill=#9b69d7 /><rect x=21 y=31 width=1 height=1 fill=#58ca7d /><rect x=21 y=39 width=1 height=1 fill=#037cb5 /><rect x=21 y=36 width=1 height=1 fill=#097454 /><rect x=21 y=28 width=1 height=1 fill=#71d744 /><rect x=21 y=38 width=1 height=1 fill=#10457c /><rect x=15 y=2 width=1 height=1 fill=#f4bf09 /><rect x=15 y=7 width=1 height=1 fill=#90357d /><rect x=15 y=27 width=1 height=1 fill=#6079ba /><rect x=15 y=5 width=1 height=1 fill=#cff723 /><rect x=15 y=17 width=1 height=1 fill=#54a6db />
```
> 2 votes

# Answer
# Python, 133 bytes

I'm not quite sure if this fits the specs, because it's on a canvas in a 40x40 area.

```
from turtle import*
from random import*
ht()
up()
speed(0)
R=randint
while 1:goto(R(0,39),R(0,39));dot(1,eval('('+'R(0,255),'*3+')'))

```

**Try it online** \- version without `eval`, which doesn't work in Trinket
> 2 votes

# Answer
# shortC, ~~66~~ 56 bytes

```
Dr rand()
AOZR"\e[%d;%dH\e[%d;4%dm ",r%40,r%40,r%2,r%8);

```

-10 bytes thanks to Dr. Rand. :P

```
A                                                                  main function
 O                                                                 for
  Z                                                                seed rand()
   R                                                               print
    "\e[%d;%dH                                                     coordinate placeholder string
              \e[%d;4%dm "                                         color placeholder string
                          ,rand()%40,rand()%40,rand()%2,rand()%8   fill placeholders
                                                                ); interpreter hole

```

No TIO link because you obviously can't print to the kind of terminal this requires online.
> 2 votes

# Answer
# Processing, 112 bytes

```
void setup(){size(40,40);}void draw(){stroke(random(255),random(255),random(255));point(random(40),random(40));}

```

I can't guarantee that every pixel is replaced every 3 minutes, but looking at it it appears to be doing so. At least the odds of it missing a pixel, out of 1600 total, updating a random one 30x per second, totaling 5400 updates per 3 minutes, makes it unlikely that one would be missed.

Ungolfed:

The program is really straightforward. Open a window at 40x40 pixels, and every frame (default 30 per second) get a random color, and draw a point at a random coordinate between 0 and the parameter. 40 for pixel coordinates, 255 for colors.

```
void setup()
{
  size(40,40);
}

void draw()
{
  stroke(random(255),random(255),random(255));
  point(random(40),random(40));
}

```
> 2 votes

# Answer
# JavaScript (ES7) + HTML using SVG, 129 + 10 = 139 bytes

SVG version, heavily inspired by @Octopus's `<canvas>` approach.

### JS

```
r=n=>n*Math.random()|0
setInterval('s.innerHTML+=`<rect x=${r(40)} y=${r(40)} fill=#${r(2**24).toString(16)} width=1 height=1>`')

```

### HTML

```
<svg id=s>

```

Since the Stack Snippet likes to break the script by parsing the `<rect>` tag, here's a CodePen.
> 2 votes

# Answer
## LOGO, 71 bytes

The only language that I know of, being not esoteric/specially designed for codegolfing, and have `forever` function. Any idea on the `map` part?

```
pu forever[setxy random 100 random 100 setpixel map[random 256][1 1 1]]

```
> 2 votes

# Answer
## Perl (on \*nix), 69 bytes

**The `\x1b`s are literal escape characters.**

Relies on `stty` command and works well on OS X.

```
{printf"\x1b[%i;%iH\x1b[48;5;%im ",map{rand$_}`stty size`=~/\d+/g,256;redo}

```

Similar to other approaches, but I liked the combination of all params into one call to `printf` so thought I'd share. Kills my terminal.

---

### Twice as many pixels, 83 bytes

```
{printf"\x1b[%i;%iH\x1b[48;5;%i;38;5;%im▄",map{rand$_}`stty size`=~/\d+/g,256,256;redo}

```

This approach uses a unicode block  and a random foreground and background colour which gives a more square pixel. Kills my terminal too, but looks cooler.
> 2 votes

# Answer
## Bash, 104 bytes

**The `\e`s are literal escape characters.**

These are pretty much translations of my Perl submission, but using bash fork bomb style syntax! Not as clever as the other bash entry that writes directly to the display I'm afraid.

```
:(){ printf "\e[%i;%iH\e[48;5;%im " $((RANDOM%`tput lines`)) $((RANDOM%`tput cols`)) $((RANDOM%256));:;};:

```

---

### More pixels, 130 bytes

Same as my Perl answer, this uses a unicode character for the foreground and colours the background of each pixel too.

```
:(){ printf "\e[%i;%iH\e[48;5;%i;38;5;%im▄" $((RANDOM%`tput lines`)) $((RANDOM%`tput cols`)) $((RANDOM%256)) $((RANDOM%256));:;};:

```
> 2 votes

# Answer
# QBIC, 34 bytes

```
screen 12{pset(_r640|,_r480|),_r16

```

Unfortunately, QBIC doesn't set a `SCREEN` mode by default, so that eats some bytes. `PSET` is an illegal command in QBIC's default graphical context.

## Explanation

```
screen 12           Set the screen to a mode supporting (colored) graphics
{                   DO until the compiler is killed by ctrl-scroll lock
pset                PSET is a QBasic command to set one pixel
(_r640|,_r480|)     it takes a set of coords (x, y) which QBIC chooses at random with _r
,_r16               and a color (1,16)

```

## Sample output

@Anonymous found an error in QBIC's `rnd()` function. Fixing that gives the output below. Thanks!
> 2 votes

# Answer
# Super Chip (48)?, 12 bytes

```
0x00FF 'enter high resolution mode (64x128 pixels)
0xA209 'set I to 0x209 (second byte of draw instruction)
0xC03F 'set register 0 to a random number from 0 to 63
0xC13F 'set register 1 to a random number from 0 to 63
0xD101 'draw a sprite. x=register 1, y=register 0, height=1
0x1204 'jump to third instruction

```

I'm not sure of the exact name, but I had to use this instead of normal Chip-8 because of the 40x40 pixel limitation.
> 2 votes

# Answer
# GW-Basic, 47 bytes (tokenised)

```
0 SCREEN 7:RANDOMIZE TIMER:WHILE 1:PSET(RND*40 MOD 40,RND*40 MOD 40),RND*16 AND 15:WEND

```

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

# Answer
# Minecraft 1.12.2, 747 bytes(compressed), 836+60(contain+filename)

```
0000h: 52 61 72 21 1A 07 01 00 F3 E1 82 EB 0B 01 05 07
0010h: 00 06 01 01 80 80 80 00 8A 2C 8F 18 25 02 03 0B
0020h: 94 01 04 94 01 20 D2 9C B3 95 80 00 00 09 6C 65
0030h: 76 65 6C 2E 64 61 74 0A 03 02 F0 E3 51 1A 04 6E
0040h: D4 01 1F 8B 08 00 34 EB D4 5B 00 FF E3 62 60 E0
0050h: 62 60 71 49 2C 49 E4 60 E0 4D 4F CD 4B 2D 4A 2C
0060h: C9 2F F2 4B CC 4D 65 60 49 CB 49 2C 61 66 E0 70
0070h: 07 72 42 2A 0B 52 19 18 18 98 99 19 D8 CB 52 8B
0080h: 8A 33 F3 F3 18 18 BC F6 72 31 70 82 24 83 4A 73
0090h: 52 8B 39 18 04 D2 81 6C 9F FC FC 02 B7 D2 BC E4
00a0h: 12 90 12 C6 44 06 66 06 B6 E0 82 C4 F2 BC 28 06
00b0h: 90 76 28 27 02 C4 01 69 80 D9 E7 5F 00 52 5F CC
00c0h: C0 69 6C 6D 64 6A A6 65 68 6D C8 C0 00 00 20 45
00d0h: 88 30 9A 00 00 00 C6 A9 60 BA 41 02 03 0B 92 01
00e0h: 04 A9 02 20 58 56 55 04 80 03 00 25 64 61 74 61
00f0h: 2F 66 75 6E 63 74 69 6F 6E 73 2F 6D 69 6E 65 63
0100h: 72 61 66 74 2F 61 2E 6D 63 66 75 6E 63 74 69 6F
0110h: 6E 0A 03 02 76 DA 2D 12 05 6E D4 01 C6 13 8F 20
0120h: 54 43 33 F6 50 34 BD 83 E0 EA 70 08 12 22 42 4A
0130h: 60 4E 1F 06 31 44 F5 04 06 DA 42 5A 88 DD 2F BB
0140h: BD 07 AD 36 E9 75 3E 23 86 E9 A6 7C 51 B9 C9 72
0150h: 8C 30 CF 07 83 D9 46 51 EB 3D C3 E1 1B 2C 6D A8
0160h: 53 C1 54 83 18 0B 1A 57 5B 63 54 F3 41 D9 97 53
0170h: AB 55 E0 F8 23 A6 81 32 D7 B0 F8 37 B8 3D 72 D5
0180h: 3A 27 98 2E 39 A2 20 68 BC BA DB FE 84 61 A0 17
0190h: 19 D0 97 3C FA 9E 71 98 92 87 6C 7C 93 DF E5 D9
01a0h: AC 8D AB 1F C7 4C FB 91 29 D4 59 3E 3B 90 1B C0
01b0h: AA 3A 41 02 03 0B E8 00 04 87 03 20 19 8F C5 65
01c0h: 80 03 00 25 64 61 74 61 2F 66 75 6E 63 74 69 6F
01d0h: 6E 73 2F 6D 69 6E 65 63 72 61 66 74 2F 62 2E 6D
01e0h: 63 66 75 6E 63 74 69 6F 6E 0A 03 02 22 1C 99 C6
01f0h: 02 6E D4 01 C6 F9 65 26 43 54 2F 76 04 3E E8 34
0200h: 3E D0 28 3E DF E5 3A A3 C9 D0 DE 0A 0F 3D BE 27
0210h: 9F C7 2F 2E B4 CC E1 30 81 32 A5 81 33 0C A0 F2
0220h: 43 EA 5B 6D 37 CA 74 CF 55 55 55 C0 BC 9E 29 49
0230h: A8 9D 7D DF 02 97 B4 1E B6 60 16 80 58 18 31 01
0240h: A3 62 07 0A 46 3C 51 E4 80 A0 08 89 E0 90 AD 7F
0250h: DF 2E AF CE 23 A6 91 E3 48 FA D0 1C BA A1 75 20
0260h: 32 02 03 0B 00 05 00 10 00 00 00 00 80 00 00 18
0270h: 64 61 74 61 2F 66 75 6E 63 74 69 6F 6E 73 2F 6D
0280h: 69 6E 65 63 72 61 66 74 0A 03 02 AD C3 9B 2D 04
0290h: 6E D4 01 C4 B1 B7 E8 28 02 03 0B 00 05 00 10 00
02a0h: 00 00 00 80 00 00 0E 64 61 74 61 2F 66 75 6E 63
02b0h: 74 69 6F 6E 73 0A 03 02 D1 6A 8E 26 25 6D D4 01
02c0h: F6 87 4C DB 1E 02 03 0B 00 05 00 10 00 00 00 00
02d0h: 80 00 00 04 64 61 74 61 0A 03 02 EE 28 D1 1F 25
02e0h: 6D D4 01 1D 77 56 51 03 05 04 00

```

To prove whole world is not always bigger (bin is .rar file)

```
level.dat
    Data
        GameRules
            gameLoopFunction: a
        GameType: 3 # so you don't fall and mob won't spawn at night
        generatorName: flat
        generatorOptions: 3;256*1;1 # full of stone
        SpawnX: 0
        SpawnZ: 0
        version: 19133 # avaliable
data
    functions
        minecraft
            a.mcfunction
                summon area_effect_cloud
                # won't show something when die
                spreadplayers 0 0 0 20 0 @e[type=!player]
                execute @r[type=!cow] ~ ~ ~ tp @s ~ ~-1 ~
                execute @r[type=!cow] ~ ~ ~ tp @s ~ ~-2 ~
                execute @r[type=!cow] ~ ~ ~ tp @s ~ ~-4 ~
                execute @r[type=!cow] ~ ~ ~ tp @s ~ ~-8 ~
                # minecraft bug, tp @r[type=!cow] ~ ~-1 ~
                # always tp player
                execute @e[type=!player] ~ ~ ~ function b
                tp @a ~ 275 ~
            b.mcfunction
                setblock ~ ~-1 ~ wool 15
                setblock ~ ~ ~ wool 14
                setblock ~ ~1 ~ wool 13
                setblock ~ ~2 ~ wool 12
                setblock ~ ~3 ~ wool 11
                setblock ~ ~4 ~ wool 10
                setblock ~ ~5 ~ wool 9
                setblock ~ ~6 ~ wool 8
                setblock ~ ~7 ~ wool 7
                setblock ~ ~8 ~ wool 6
                setblock ~ ~9 ~ wool 5
                setblock ~ ~10 ~ wool 4
                setblock ~ ~11 ~ wool 3
                setblock ~ ~12 ~ wool 2
                setblock ~ ~13 ~ wool 1
                setblock ~ ~14 ~ wool

```

# Minecraft 1.12.2, 806 bytes(compressed), 1352+60(contain+filename)

```
0000h: 52 61 72 21 1A 07 01 00 F3 E1 82 EB 0B 01 05 07
0010h: 00 06 01 01 80 80 80 00 33 72 E7 9F 41 02 03 0B
0020h: 9E 01 04 EF 02 20 EC 92 16 D1 80 03 00 25 64 61
0030h: 74 61 2F 66 75 6E 63 74 69 6F 6E 73 2F 6D 69 6E
0040h: 65 63 72 61 66 74 2F 61 2E 6D 63 66 75 6E 63 74
0050h: 69 6F 6E 0A 03 02 E4 73 98 96 26 6D D4 01 C3 02
0060h: 9B 26 54 34 33 F6 60 34 BD 83 E0 EA 70 08 12 39
0070h: 28 94 C0 7C 3E 10 66 FE 16 83 86 B6 99 BF 88 E6
0080h: D3 3B BB 70 16 9A C8 4B E7 0E 41 82 48 CF 65 19
0090h: C9 73 C2 CC A1 21 60 7A 8F 07 DC 61 F1 C3 02 C4
00a0h: 10 E1 45 C2 C6 0A A1 72 9A 51 5D 75 32 F6 B4 37
00b0h: D9 C0 39 51 69 A4 D3 32 26 D7 53 D4 46 24 91 91
00c0h: 60 49 F1 31 DF E4 5E 70 D6 7D 20 17 39 24 6C 1F
00d0h: 47 FA 30 10 B5 DD A1 2C 87 AE E3 0C FB 87 BA 67
00e0h: E9 72 6A 24 2E D8 EB 5F F2 E3 FC 1B 66 9C F4 E9
00f0h: AA 3A FB 3C FA 7B 23 89 D4 8E E8 90 4C 1E F8 90
0100h: 41 02 03 0B 9C 01 04 CA 06 20 D0 72 7A 6E 80 03
0110h: 00 25 64 61 74 61 2F 66 75 6E 63 74 69 6F 6E 73
0120h: 2F 6D 69 6E 65 63 72 61 66 74 2F 62 2E 6D 63 66
0130h: 75 6E 63 74 69 6F 6E 0A 03 02 5E 12 89 DC 26 6D
0140h: D4 01 C7 04 99 26 54 33 33 F6 60 44 DF 42 F0 77
0150h: C1 1B 71 D9 F8 D1 42 F0 FA 52 8E BA B5 56 0E 0D
0160h: 4A 5B 74 DE F1 9A 23 93 54 07 17 13 42 46 02 5E
0170h: D4 BD C8 F3 F2 96 06 70 5F 7B EE 24 78 CC 9F E7
0180h: 18 BF F1 4C D4 BD 69 BA 63 A1 F1 E0 5F 4A 1E F2
0190h: 2A 4D 5F D4 EA 59 96 5E 23 28 7A A4 B4 AF 92 94
01a0h: 76 74 EA 70 94 CB BB F9 B3 97 64 00 AC F6 EE 0D
01b0h: C1 B8 65 81 D8 31 A1 B4 63 03 60 C5 86 B1 78 24
01c0h: 2C 2B 86 F0 AF 17 70 57 0B B4 2B 45 A4 85 AE 87
01d0h: A4 87 57 42 24 83 AE 82 49 03 B8 80 4B E6 66 BD
01e0h: 96 D5 25 02 03 0B 8F 01 04 8F 01 20 83 7C 6D FD
01f0h: 80 00 00 09 6C 65 76 65 6C 2E 64 61 74 0A 03 02
0200h: 10 70 3C 51 27 6D D4 01 1F 8B 08 00 C9 78 D3 5B
0210h: 00 FF 35 8D 41 0A C2 30 14 44 47 D2 6A 1A 28 78
0220h: 14 C5 65 B7 62 41 A4 05 75 21 EE 3E F2 5B 84 9A
0230h: 84 24 55 3C 9C 77 B3 1F 74 37 8F 79 C3 18 C0 20
0240h: DB 52 22 8D B2 67 CB 81 92 0B 0D 3D 18 59 37 50
0250h: 52 D0 F5 04 E7 B7 67 00 4A 61 F1 E4 10 EF CE 02
0260h: FB 8F 41 21 E5 71 1C 38 6A 2C FB 29 1F 9C F3 BB
0270h: D1 DE 92 28 33 82 C2 FC E4 E9 65 AF 90 F9 0F 2E
0280h: 02 32 F8 FF B5 5E FC 88 7C 53 AD AA 35 F0 05 F9
0290h: 41 3F 00 96 00 00 00 1B 7A 52 1B 32 02 03 0B 00
02a0h: 05 00 10 00 00 00 00 80 00 00 18 64 61 74 61 2F
02b0h: 66 75 6E 63 74 69 6F 6E 73 2F 6D 69 6E 65 63 72
02c0h: 61 66 74 0A 03 02 BB 8F 67 2F 25 6D D4 01 C4 B1
02d0h: B7 E8 28 02 03 0B 00 05 00 10 00 00 00 00 80 00
02e0h: 00 0E 64 61 74 61 2F 66 75 6E 63 74 69 6F 6E 73
02f0h: 0A 03 02 D1 6A 8E 26 25 6D D4 01 F6 87 4C DB 1E
0300h: 02 03 0B 00 05 00 10 00 00 00 00 80 00 00 04 64
0310h: 61 74 61 0A 03 02 EE 28 D1 1F 25 6D D4 01 1D 77
0320h: 56 51 03 05 04 00

level.dat
    Data
        GameRules
            gameLoopFunction: a
        GameType: 3 # so you don't fall and mob won't spawn at night
        generatorName: flat
        generatorOptions: 3;0;1 # just air
        SpawnX: 0
        SpawnZ: 0
        version: 19133 # avaliable
data
    functions
        minecraft
            a.mcfunction
                summon area_effect_cloud
                # won't show something when die
                fill -20 3 -20 20 3 20 wool
                # init. A .mca is at least 12KB too expensive
                # (though flat generation may work fine)
                scoreboard objectives add a dummy
                execute @r[type=!cow] ~ ~ ~ scoreboard players add @s a 1
                execute @r[type=!cow] ~ ~ ~ scoreboard players add @s a 2
                execute @r[type=!cow] ~ ~ ~ scoreboard players add @s a 4
                execute @r[type=!cow] ~ ~ ~ scoreboard players add @s a 8
                # minecraft bug, scoreboard players add @r[type=!cow] a 1
                # always add score to player
                execute @e[type=!player] ~ ~ ~ function b
            b.mcfunction
                spreadplayers 0 0 0 20 0 @s
                execute @s ~ 4 ~ setblock ~ ~ ~ wool
                # setblock ~ 4 ~ wool uses the old location
                execute @s[score_a=15] ~ 4 ~ setblock ~ ~ ~ wool 15
                execute @s[score_a=14] ~ 4 ~ setblock ~ ~ ~ wool 14
                execute @s[score_a=13] ~ 4 ~ setblock ~ ~ ~ wool 13
                execute @s[score_a=12] ~ 4 ~ setblock ~ ~ ~ wool 12
                execute @s[score_a=11] ~ 4 ~ setblock ~ ~ ~ wool 11
                execute @s[score_a=10] ~ 4 ~ setblock ~ ~ ~ wool 10
                execute @s[score_a=9] ~ 4 ~ setblock ~ ~ ~ wool 9
                execute @s[score_a=8] ~ 4 ~ setblock ~ ~ ~ wool 8
                execute @s[score_a=7] ~ 4 ~ setblock ~ ~ ~ wool 7
                execute @s[score_a=6] ~ 4 ~ setblock ~ ~ ~ wool 6
                execute @s[score_a=5] ~ 4 ~ setblock ~ ~ ~ wool 5
                execute @s[score_a=4] ~ 4 ~ setblock ~ ~ ~ wool 4
                execute @s[score_a=3] ~ 4 ~ setblock ~ ~ ~ wool 3
                execute @s[score_a=2] ~ 4 ~ setblock ~ ~ ~ wool 2
                execute @s[score_a=1] ~ 4 ~ setblock ~ ~ ~ wool 1

```
> 2 votes

# Answer
# Powershell, ~~128~~ ~~126~~ ~~124~~ 88 bytes

*-2 bytes thanks @Veskah*

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

```

Output:

VS code output:
> 2 votes

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

```
> 2 votes

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

```
For(I,0,62
For(J,0,94
If int(2rand
Pxl-Change(I,J
End
End
prgmC

```

where `C` is the name of the program.

Without calling itself (+2 bytes):

```
While 1
For(I,0,62
For(J,0,94
If int(2rand
Pxl-Change(I,J
End
End
End

```

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

# Answer
# R, ~~143~~ 138 bytes

*-4 bytes thanks to user2390246*

```
r=runif
s=sample
g=1600
x=1:40
k=hsv(r(g),r(g),r(g))
while(1){image(x,x,matrix(1:g,40),c=k)
Sys.sleep(99/g)
k[s(g,1)]=hsv(r(1),r(1),r(1))}

```

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

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

**breakdown**

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

```
> 1 votes

# Answer
# 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();}}

```

**Explanation:**

```
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
        M.this.g.setFill(javafx.scene.paint.Color.color(Math.random(),Math.random(),Math.random()));
                                            //     Set a random color
        M.this.g.fillRect((int)(Math.random()*40),(int)(Math.random()*40),1,1);
                                            //     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

```

**Output:**
> 1 votes

# Answer
## Mathematica 112 Bytes

```
r:=RandomReal[];b:=⌈40r⌉;a=r&~Array~{40,40,3};Dynamic[a[[b,b]]={r,r,r};ArrayPlot[a,ColorFunction->RGBColor]]

```

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!
> 1 votes

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

```
s=[]
80.times{|x|60.times{|y|s<<Square.new(x:x*8,y:y*8,size:8)}}
update{s.sample.color='random'}
show

```
> 1 votes

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

```

TryItOnline
> 1 votes

# Answer
# Ruby, 78 Bytes

```
loop{print"\e[#{rand(41)};#{rand(41)}H\e[#{rand(30..37)};#{rand(1..3)}m█\e[0m"}

```

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:

(result may vary depending on terminal and color scheme)

Explanation

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

```
> 1 votes

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

# Answer
# 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(;;) {
                        i.setRGB(
                             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
            }
        };
    }
}

```

Result:
> 1 votes

# Answer
# 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))])

```

Ungolfed:

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

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

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

```
> 1 votes

# Answer
## 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 *
h=200
w=200
c=zeros((h,w,3),"u1")
R=random.randint
while 1:
    c[R(h),R(w)]=R(256,size=3)
    imshow("",c)
    waitKey(1)

```
> 0 votes

# Answer
# Python 3 with Pygame, 171 Bytes

```
import pygame as p,random as r
r=r.randint
a=p.PixelArray(p.display.set_mode((40,40)))
while(1):
    a[r(0,39),r(0,39)]=(r(0,255),r(0,255),r(0,255))
    p.display.update()

```
> 0 votes

# Answer
# 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)]]
upd}

```

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

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

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

```
> 0 votes

# Answer
## 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.
> 0 votes

---
Tags: code-golf, graphical-output, random, color
---


# Question
Title: How far away is n to the next power of b?
Let `n` and `b` be positive integers larger than `1`.

Output the distance from `n` to the next power of `b`.

For `n=5` and `b=3`, the next power of `3` from `5` is `9` (`3^2 = 9`), so the output is `9 - 5 = 4`.

For `n=8` and `b=2`, the next power of `2` from `8` is `16` (`2^4 = 16`), so the output is `16 - 8 = 8`. Note that `n` is a power of `2` in this example.

Testcases:

```
  n b output
212 2 44
563 5 62
491 5 134
424 3 305
469 8 43
343 7 2058
592 7 1809
289 5 336
694 3 35
324 5 301
  2 5 3

```

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
> 17 votes
# Jelly,  ~~4~~  3 bytes

```
ạæċ

```

A dyadic link taking `n` on the left and `b` on the right and returning the result.

**Try it online!**

### How?

```
ạæċ - Link: number n, number b | n,b ∈ ℕ
 æċ - ceiling n to the next power of b
ạ   - absolute difference between n and that

```

# Answer
> 8 votes
## x86-64 Assembly (Windows x64 Calling Convention), 14 13 bytes

An inefficient (but svelte!) iterative approach (with credit to @Neil for inspiration):

```
               HowFarAway PROC
6A 01             push   1
58                pop    rax         ; temp = 1
               Loop:
0F AF C2          imul   eax, edx    ; temp *= b
39 C8             cmp    eax, ecx
72 F9             jb     Loop        ; keep looping (jump) if temp < n
29 C8             sub    eax, ecx    ; temp -= n
C3                ret                ; return temp
               HowFarAway ENDP

```

The above function takes two integer parameters, `n` (passed in the `ECX` register) and `b` (passed in the `EDX` register), and returns a single integer result (in the `EAX` register). To call it from C, you would use the following prototype:

```
unsigned HowFarAway(unsigned n, unsigned b);

```

This is limited to the range of a 32-bit integer. It can be easily modified to support 64-bit integers by using the full long registers, but it would cost more bytes to encode those instructions. :-)

# Answer
> 6 votes
# Dyalog APL, 10 bytes

*2 bytes saved thanks to @ZacharyT*

```
⊢-⍨⊣*1+∘⌊⍟

```

Try it online!

Takes `n` as right argument and `b` as left argument.

Calculates `b<sup>⌊log<sub>b</sub>n + 1⌋</sup> - n`.

# Answer
> 6 votes
# C (gcc), ~~39~~ 35 bytes

New undefined behavior thanks to Erik

```
f(n,b,i){for(i=b;b<=n;b*=i);n=b-n;}

```

Try it online!

# Answer
> 6 votes
# , ~~38~~ 34 bytes

```
pryr::f({a=b^(0:n)-n;min(a[a>0])})

```

Anonymous function. Stores all values of b to the power of everything in the range \[0,n\], subtracts n from each, subsets on positive values, and returns the min.

TIO has a non-pryr version, called as `f(n,b)`; this version needs to be called as `f(b,n)`.

Saved 4 bytes thanks to Jarko Dubbeldam, who then outgolfed me.

Try it online!

# Answer
> 4 votes
# Cubix, ~~24~~ 20 bytes

*-4 bytes thanks to MickyT*

```
Pwp.I|-.;)^0@O?|uq;<

```

Reads in input like `n,b`

Fits on a 2x2x2 cube:

```
    P w
    p .
I | - . ; ) ^ 0
@ O ? | u q ; <
    . .
    . .

```

### Explanation:

`I|I0` : read the input, push 0 (counter) to the stack

`^w` puts the IP to the right place for the loop:

* `Pp-` : compute `b^(counter)`, move `n` to top of stack, compute `b^(counter) - n`
* `?` : turn left if negative, straight if 0, right if positive
    + Positive: `O@` : output top of stack (distance) and exit.
    + Negative : `|?` : proceed as if the top of the stack were zero
* `<;qu;)` : point the IP in the right direction, pop the top of the stack (negative/zero number), move `n` to the bottom of the stack, u-turn, pop the top of the stack (`b^(counter)`) and increment the counter
* IP is at `^w` and the program continues.

Watch it online!

Try it online!

# Answer
> 3 votes
# Haskell, 20 bytes

```
n%b=until(>n)(*b)1-n

```

Try it online!

`until` saves the day

# Answer
> 3 votes
# R, 30 bytes

```
pryr::f(b^floor(log(n,b)+1)-n)

```

Evaluates to the function

```
function (b, n)
b^floor(log(n, b) + 1) - n

```

Which takes the first power greater or equal than `n`, and then substracts `n` from that value.

Changed `ceiling(power)` to `floor(power+1)` to ensure that if `n` is a power of `b`, we take the next power.

# Answer
> 2 votes
# 05AB1E, ~~9~~ 8 bytes

```
sLmʒ‹}α¬

```

Try it online!

**Explanation**

```
s         # swap order of the inputs
 L        # range [1 ... n]
  m       # raise b to each power
   ʒ‹}    # filter, keep only the elements greater than n
      α   # calculate absolute difference with n for each
       ¬  # get the first (smallest)

```

# Answer
> 2 votes
# MATL, ~~10~~ 9 bytes

```
yy:YAn^w-

```

Try it online!

### Explanation

Consider inputs `694` and `3` as an example.

```
y    % Implicitly take two inputs. Duplicate from below
     % STACK: 694, 3, 694
y    % Duplicate from below
     % STACK: 694, 3, 694, 3
:    % Range
     % STACK: 694, 3, 694, [1 2 3]
YA   % Base conversion (of 694 with "digits" given by [1 2 3]
     % STACK: 694, 3, [3 3 2 3 1 2]
n    % Number of elements
     % STACK: 694, 3, 6
^    % Power
     % 694, 729
w    % Swap
     % STACK: 729, 694
-    % Subtract. Implicitly display
^    % 35

```

# Answer
> 2 votes
# C, ~~42~~ 40 bytes

Thanks to commenter @Steadybox for the tip

```
o;p(n,b){for(o=b;n>=b;)b*=o;return b-n;}

```

# Answer
> 2 votes
# Mathematica, 24 bytes

```
#2^⌊1/#~Log~#2⌋#2-#&

```

thanks Martin

**I/O**

> \[343, 7\]
>
> 2058

# Answer
> 2 votes
# Java (OpenJDK 8), 42 bytes

*Based on @GovindParmar's C answer.*

```
n->b->{for(int o=b;n>=b;b*=o);return b-n;}

```

Try it online!

# Answer
> 2 votes
# Python 2,  ~~42 41~~  35 bytes

Saved 6 thanks to loopy walt! (A superior recursive algorithm.)

```
f=lambda n,b:n<1or b*f(n/b,b)-(n%b)

```

A recursive function which repeatedly integer divides by `b` until that yields `0` (`n<1`) yielding `1` (well, `True` which works like `1`) at the tail and multiplies back up by `b` removing the remainder after division by `b` at each step. That is, we subtract `n` from `b^k` in base `b`, "digit" by "digit".

**Try it online!**

# Answer
> 2 votes
# JavaScript (ES6), 29 bytes

Very similar to Rick's approach but posted with his permission (and some help saving a byte).

```
n=>b=>g=(x=b)=>x>n?x-n:g(x*b)

```

---

## Try it

```
f=
n=>b=>g=(x=b)=>x>n?x-n:g(x*b)
oninput=_=>o.value=f(+i.value)(+j.value)()
o.value=f(i.value=324)(j.value=5)()
```

```
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
```

```
<label for=i>n: </label><input id=i type=number><label for=j>b: </label><input id=j type=number><label for=o>= </label><input id=o>
```

# Answer
> 2 votes
# Japt, ~~16~~ 8 bytes

~~This feels longer than it needs to be!~~ That's a bit better!

```
nVpUìV l

```

Try it

```
nVpUìV l     :Implicit input of integers U=n & V=b
n            :Subtract U from
 Vp          :  Raise V to the power of
   UìV       :    Convert U to a base-V digit array
       l     :    Get the length

```

# Answer
> 2 votes
# AWK, ~~34~~ 32+2 bytes

```
{for(n=$2;n<=$1;n*=$2);}$0=n-$11

```

Try it online!

Requires the `-M` option for arbitrary precision to handle the `12345678901234567890 1000000 => 999987654321098765432110` case.

The non-loop version requires the same number of bytes:

```
$0=$2^int(log($1)/log($2)+1)-$1

```

After almost 5 years, saved 2 bytes in each formulation by removing unnecessary grouping symbols. Thanks @PaoloVlw

# Answer
> 2 votes
# Vyxal, 8 bytes

```
ɾe'¹>;hε

```

Try it Online!

Port of 05AB1E.

## How?

```
ɾe'¹>;hε
ɾ        # Inclusive range from one to (implicit) first input
 e       # For each element, push it to the power of the (implicit) second input
  '¹>;   # Filter for only elements greater than the first input
      h  # Get the first item
       ε # Get the absolute difference of the first item and the (implicit) first input

```

# Answer
> 2 votes
# Desmos, ~~30~~ 27 bytes

```
f(n,b)=b^{floor(log_bbn)}-n

```

Try It On Desmos

-3 thanks to @Aiden Chow and @Steffan

Gotta love using your favorite graphing calculator for code golf. Taken from the R answer.

# Answer
> 1 votes
# JavaScript (ES6), 31 bytes

```
f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i)

```

**Test cases:**

```
f=(n,b,i=b)=>b>n?b-n:f(n,b*i,i)

console.log(f(212, 2)) // 44
console.log(f(563, 5)) // 62
console.log(f(491, 5)) // 134
console.log(f(424, 3)) // 305
console.log(f(469, 8)) // 43
console.log(f(343, 7)) // 2058
console.log(f(592, 7)) // 1809
console.log(f(289, 5)) // 336
console.log(f(694, 3)) // 35
console.log(f(324, 5)) // 301
```

# Answer
> 1 votes
# Octave, 32 bytes

```
@(n,b)b^(fix(log(n)/log(b))+1)-n

```

Try it online!

# Answer
> 1 votes
# Octave, 26 bytes

```
@(n,b)b^sum(b.^(0:n)<=n)-n

```

Verify all test cases!

# Answer
> 1 votes
# Ruby, 38 bytes

Two different approaches:

```
->(n,b){p b**(Math.log(n,b).to_i+1)-n}

```

Try it online!

```
->(n,b){p b**(0..n).find{|x|b**x>n}-n}

```

Try it online!

# Answer
> 1 votes
# Japt, 9 bytes

```
_q}a@nVpX

```

Test it online!

### Explanation

```
_  q}a@  nVpX
Z{Zq}aX{UnVpX}  // Ungolfed
                // Implicit: U, V = input integers
     aX{     }  // For each integer X in [0...1e9), take
          VpX   //   V to the power of X
        Un      //   minus U,
Z{  }           // and return the first one Z where
  Zq            //   Math.sqrt(Z) is truthy.
                //   Math.sqrt returns NaN for negative inputs, and 0 is falsy, so this is
                //   truthy iff Z is positive. Therefore, this returns the first positive
                //   value of V**X - U.
                // Implicit: output result of last expression

```

# Answer
> 1 votes
# Haskell, 31 bytes

```
f n b=[b^x-n|x<-[1..],b^x>n]!!0

```

Try it online!

# Answer
> 1 votes
# Perl 6,  ~~31 30~~  29 bytes

```
->\n,\b{(b,b* *...*>n).tail -n}

```

Test it (31)

```
->\n,\b{b**(log(n,b).Int+1)-n}

```

Test it (30)

```
{$^b**(log($^a,$b).Int+1)-$a}

```

Test it (29)

```
{($^b,$b* *...*>$^a).tail-$a}

```

Test it (29)

# Answer
> 1 votes
# PARI/GP, ~~26~~ 24 bytes

```
f(n,b)=b^logint(b*n,b)-n

```

# Answer
> 1 votes
# Brachylog, 7 bytes

```
^ʰ↙X>₁-

```

Try it online!

Takes input as a list `[b, n]`.

```
    >₁     n is strictly less than
^ ↙X       some power of
 ʰ         b,
      -    and their difference is
           the output.

```

# Answer
> 1 votes
# Forth (gforth), 45 bytes

```
: f >r 1 begin i * 2dup < until rdrop - abs ;

```

Try it online!

### Code Explanation

```
: f          # start a new word definition
  >r         # store b on the return stack for quick access
  1          # create a counter to store powers of b
  begin      # start an indefinite loop
    i *      # multiply the counter by b
    2 dup <  # duplicate the counter and n. Check if n is less than the counter
  until      # if it is, end the loop
  rdrop      # remove b from the return stack
  - abs      # subtract and get absolute value (avoid negative)
;            # end the word definition

```

# Answer
> 1 votes
# Husk, 6 bytes

```
≠Ω>¹*³

```

Try it online!

```
≠Ω>¹*³      # ¹ and ³ duplicate arguments ⁰ and ², so parses as:
≠Ω>⁰*²²⁰
            # now:
 Ω>⁰*²²     # Ω = Iterate function f until test result t is truthy, starting with x:
      ²     #     x is arg 2
    *²      #     f is *² = times arg 2, so iterating generates power series of arg 2
  >⁰        #     t is >⁰ = greater than arg 1
            # then:
≠           # get the absolute difference to
       ⁰    # arg 1

```

# Answer
> 0 votes
# PHP\>=7.1, 46 bytes

```
for([,$n,$b]=$argv;0>=$d=$b**$i++-$n;);echo$d;

```

PHP Sandbox Online

# Answer
> 0 votes
# Python 3, 50 48 bytes

Thanks to EriktheOutgolfer for saving 2 bytes!

```
lambda n,b:b**-~int(math.log(n,b))-n
import math

```

Try it online!

Python doesn't have any fancy log or ceiling builtins, so I just went with the obvious approach with a little bit of golfing flair.

# Answer
> 0 votes
## Lua, ~~74~~ 73 Byte

A straight forward solution, I'm using 10 bytes to ensure that the arguments are treated as numbers, and not strings. Outputs to STDIN.

**Edit: forgot to remove the space in `w=1 n=n+0`, saves one byte**

```
n,b=...b=b+0p=b w=1n=n+0while p<=n do p=math.pow(b,w)w=w+1 end print(p-n)

```

### Explained

Try it online!

```
n,b=...           -- unpack the argument into the variable n and b
b=b+0             -- set b's type to number
n=n+0             -- set n's type to number
p=b               -- set a variable to track the current value of the powered b
w=1               -- set the nth power
while p<=n        -- iterate untill the current power is greater or equals to n
do
  p=math.pow(b,w) -- raise b to the power w
  w=w+1           -- increment w
end
print(p-n)        -- outputs p minus the following power of b

```

# Answer
> 0 votes
# Python 2, ~~48~~ 41 bytes

* @Rod's loop simplification saved 7 bytes!

Full program without recursion or bit twiddling:

```
i=1;n,b=input()
while n>=i:i*=b
print i-n

```

Try it online!

Input format: `n, b`.

# Answer
> 0 votes
# QBIC, 23 bytes

```
{p=:^q~p>:|_xp-b|\q=q+1

```

Takes parameter `b` first, then `n`.

## Explanation

```
{       DO
p=:^q   SET p to input b (read as 'a' by QBIC fromt he cmd line) ** q (starts as 1)
~p>:    IF p exceeds 'n' (read as 'b' by QBIC fromt he cmd line)
|_xp-b| THEN QUIT, printing p minus b
\q=q+1  ELSE increase q, re-run

```

# Answer
> 0 votes
# Common Lisp, 73 bytes

```
(defun f(n b)(setq a b)(loop(when(> b n)(return(- b n)))(setq b(* b a))))

```

Try it online!

# Answer
> 0 votes
# , 17 bytes

```
[-~]^[:>.]^.[:>:[

```

## Usage

```
   f =: [-~]^[:>.]^.[:>:[
   424 f 3
305

```

## Explanation

Performs `pow(b, ceil(log(n+1)))` where `log` has base `b`.

# Answer
> 0 votes
# dc, 23 bytes

```
snsb1[lb*dln!<F]dsFxln-

```

I had hoped to be able to use `Z` to count digits in a given radix, but it seems to count only in decimal. And we might want a base larger than dc supports. So this takes the obvious approach of successively multiplying by `b` until a value larger than `n` is reached, at which point we subtract `n` and leave the result at top of stack.

Annoyingly, we need `!<` rather than `>` comparison because the condition excludes an answer of 0.

## Demo

```
for i in '212 2' '563 5' '491 5' '424 3' '469 8' '343 7'\
         '592 7' '289 5' '694 3' '324 5' '2 5' \
         '12345678901234567890 1000000'
do printf '%s => ' "$i"; dc -e '?rsnsb1[lb*dln!<F]dsFxln-p' <<<"$i"
done

```

```
212 2 => 44
563 5 => 62
491 5 => 134
424 3 => 305
469 8 => 43
343 7 => 2058
592 7 => 1809
289 5 => 336
694 3 => 35
324 5 => 301
2 5 => 3
12345678901234567890 1000000 => 999987654321098765432110

```

# Answer
> 0 votes
## TXR Lisp, 51 bytes

```
(defun f(n b)(-[(ginterate(op >= n)(op * b)1)-1]n))

```

Legend: ginterate, op.

# Answer
> 0 votes
# APL(NARS), 13 chars, 26 bytes

```
{-⍺-⍵*1+⌊⍵⍟⍺}

```

test:

```
  f←{-⍺-⍵*1+⌊⍵⍟⍺}
  212 f 2
44
  563 f 5
62
  592 f 7
1809

```

# Answer
> 0 votes
# JavaScript (ES6), 49 bytes

```
f=(n,b)=>b**(m=Math).floor(m.log(n)/m.log(b)+1)-n

```

# Answer
> 0 votes
# Python 3, 48 bytes

```
lambda n,b:b**int(math.log(n,b)+1)-n;import math

```

Try it online!

I really wish `log` was builtin

# Answer
> 0 votes
# Perl 5 `-pa`, 28 bytes

```
$.*=$F[1]until$.>$_;$_=$.-$_

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 25 bytes

```
n\b=b^floor(1+log(b,n))-n

```

Try it online!

---
Tags: code-golf, arithmetic
---