Random CSS Color code

This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this:

'#'+(Math.random()*0xffffff).toString(16).slice(-6)


If you are not familiar with CSS color code read documentations here.

Can we do better? What about other languages?

• Yours is broken, you're missing a + after the '#' – Doorknob Sep 16 '13 at 22:29
• You can remove the slice by doing this #'+(Math.random()*0xffffff|0).toString(16) – Griffin Sep 17 '13 at 10:39
• What is the "0xffffff" needed for? I'm not seeing much of a difference in my results without it. – path411 Sep 17 '13 at 22:18
• @path411 Theoretically, Math.random().toString(16) can produce a representation with less than 6 hex-digits after the (hexa)decimal point, in which case the function would break. For example, 0.1658172607421875 becomes 0.2A73 in hex. – primo Sep 18 '13 at 8:51
• Linked from Random color generator. – Peter Mortensen Jan 12 at 3:01

PHP 23 bytes

#<?=md5(rand())&ÿÿÿÿÿÿ;


Where ÿ is character 255. Bitwise and will truncate the string returned from md5, which is already in hexadecimal format.

• This is one of my favourite solutions on the site. – Griffin Sep 17 '13 at 10:08

Three character codes are valid too, so I can save some chars (4095 == 0xfff):

Ruby, 242322 18

'#%03x'%rand(4095)


If I have to use a 6-char one, then:

Ruby, 28272624 20

Shaved one character off because 8**8-1 == 0xffffff

'#%06x'%rand(8**8-1)


Thanks to chron for the format string, saving 4 chars!

Cheating (with this xkcd strip in mind):

Ruby/JS/Python/Perl/lots more, 6 (or 5)

"#a83"


I assure you, I generated it randomly!

An even cheatier version:

"red"

• You don't need parentheses for method calls in Ruby, right? – Mohsen Sep 16 '13 at 22:50
• @Mohsen Yes, but Ruby gets confused and thinks I'm calling to_s on 4095 if I omit them. – Doorknob Sep 16 '13 at 22:51
• You can get it down to 20 with a sprintf format string: '#%06x'%rand(8**8-1) – Paul Prestidge Sep 17 '13 at 0:04
• @chron Nice, thanks! Editing – Doorknob Sep 17 '13 at 0:05

Javascript

'#'+Math.random().toString(16).substr(2,6)


Just a little shorter at 42.

function randomColor() {
return '#' + Math.random().toString(16).substr(2, 6);
}

for (var n = 0; n < 16*9; n++) {
var el = document.createElement('SPAN');
el.style.backgroundColor = randomColor();
document.getElementById('demo').appendChild(el);
}
span { width: calc(100%/16);
height: calc(100vh/9);
margin-top: -7px;
display: inline-block;
}
<div id='demo'></div>

• I'm not sure why this was downvoted. It works fine in every browser I've tested. +1 – primo Sep 17 '13 at 6:11
• #'+Math.random().toString(16).slice(-6) – Mohsen Sep 17 '13 at 22:30
• @Mohsen nice! Didn't know slice could do negatives. – tristin Sep 18 '13 at 1:08
• – Peter Mortensen Jan 12 at 3:00

Fish 79

vnnnnnnnn
601234567;
>xxxxxxxx<
89""""""?
nnABCDEF:
vv""""""-
vvoooooo1
>>>>>>>>^


Not the shortest solution in the world, but it was fun to code :)

It's also not a uniform distribution, but all outputs have a non-zero probability 7 and F are most likely digits.

Outputs:

python fish.py randomColor.fish
07FFF7

python fish.py randomColor.fish
07EFD7

python fish.py randomColor.fish
366F67

python fish.py randomColor.fish
977FD7

python fish.py randomColor.fish
97F7F7

python fish.py randomColor.fish
87F6FF


PowerShell, 28 24 bytes

-4 bytes thanks to @Julian!

"#{0:X6}"-f(random 16MB)


Try it online!

• You can omit the -ma as it is implicit and save 4 bytes – Julian Jun 2 at 2:55

VyxalṪ, 8 7 bytes

\#k66ƈṅ


Try it Online!

\#      # Push a #
6ƈ  # Choose six...
k6    # Hex digits
ṅ # Appended to the #

• You can outsource a byte to a flag using this method: Try it Online! – Underslash Jul 15 at 8:45
• @Underslash Nice, thanks! – A username Jul 15 at 8:52

APL (17)

'#',(⎕D,⎕A)[6?16]


Explanation:

• 6?16: 6 random numbers from 1 to 16
• ⎕D,⎕A: the digits (0..9) followed by the alphabet (A..Z) (but only the first 16 values are ever used, i.e. 0..F)
• '#',: add a # to the front
• 6?16 is 6 non-repeating random values though, that narrows the colorspace a bit... – mniip Feb 17 '14 at 15:27

Python 3, 44 bytes

from secrets import*
print("#"+token_hex(3))


Try it online!

Did you know this built-in python module? It was added in python 3.6 to include some random function for paswords (more informations here).

How it works ?

Basicaly, I generate a random 3-bytes long hexadecimal string ... Yeah, that's it.

Python 2, 32 31 bytes

I also have the slightly less elegant : (also works in Python3 in 34 33 bytes by adding parenthesis for the print function)

print"#%06x"%((id(0)>>16)%8**8)


Try it online!

This one uses the fact that at each execution of the code, python uses an indivdual memory address for each object. This memeory address change at each execution of the program. As the last 16 bits of this id are not random, I shifted the result before using a modulo to have the right number of bits

Thanks to pxeger for -1 bytes

• You can use id(0) for -1 byte, though I'm not sure relying on ASLR alone is necessarily a valid random source. (Python doesn't "assign an id number", it uses the memory address of the object, which is assigned by the kernel, and is typically only a bit random, so it's really only suitable for seeding a PRNG) – pxeger Jun 1 at 13:51
• @pxeger I don't know if it is a valid random source, but it seems that it choose evenly a number on the wanted interval at each execution. As I saw the same trick on other problems using random, I thought I could use it here. Otherwise I have also my first solution :p – Jakque Jun 1 at 15:09

VyxalṪ, 7 bytes

\#6(k6℅


Try it Online!

Explanation

\#6(k6℅
\#      Push "#"
(    For _
6     in range(6):
k6    "0123456789abcdef"
℅   Random item

Ṫ Concatenate the stack


Bash (51)

od -N4 -An -tx /dev/urandom | cut -c2-7 | sed s/^/#/


Python 3, 53 bytes

from random import*;print(f"#{randint(0,16**6):06x}")


Try it online!

Zsh, 37 bytes

<<<\#tr -dc 0-9a-f</*/ur*m|head -c6


Try it online!

• </*/ur*m: input from /dev/urandom (shortened with wildcards)
• tr -dc 0-9a-f: keep only characters in the range 0-9a-f
• head -c6: take the first 6 characters
• <<<#: prepend # and print

Nim, 57 bytes

import colors,random
randomize()
echo 0xffffff.rand.Color


Try it online!

Jelly, 9 bytes

6ØhX¤€”#;


Try it online!

Explanation

6ØhX¤€”#;   Main niladic link
6           6
€      Map
¤       (
Øh           "0123456789abcdef"
X          Choose random
¤       )
;   Prepend
”#      "#"


Julia 1.0, 24 bytes

'#'repr(rand(UInt))[3:8]


Try it online!

Japt-P, 11 bytes

Gö6 msG i'#


Test it

Python 3, 50 bytes

import time
print(f"#{int(time.time()%16**6):6x}")


Try it online!

Random generation by modulo of current time saves two precious bytes

Also 0 before 06x can be omitted

• using f"{i:6x} will give leading spaces instead of 0 when i is less than 6 digits long in hexadecimal. You should instead use the format f"{i:06x}. But you also can gain 1 byte by replacing 16**6 by 8**8 an 2 bytes using "%06x"%i instead using the previous f-string syntax : Try it online! – Jakque Jun 1 at 10:13