| Bytes | Lang | Time | Link |
|---|---|---|---|
| 076 | AWK | 241118T174435Z | xrs |
| nan | 250921T092205Z | Miro Jon | |
| 103 | Python 3.8 prerelease | 241001T132151Z | Malo |
| 117 | Typst | 241025T152839Z | Wallbrea |
| 097 | Python 3 | 241022T204706Z | movatica |
| 075 | C | 241021T124112Z | halperyo |
| 136 | C# | 241013T191249Z | Ezlandin |
| 037 | Ruby p | 241010T184216Z | Jordan |
| 027 | Vyxal Ḣso | 240927T231612Z | emanresu |
| 030 | Japt | 240927T135632Z | Shaggy |
| 026 | 05AB1E | 240927T151859Z | Kevin Cr |
| 135 | Haskell | 241001T004636Z | Antonio |
| 033 | Perl 5 + p | 240930T091109Z | Dom Hast |
| 083 | Wolfram Language Mathematica | 240929T192146Z | att |
| 030 | Uiua | 240928T164813Z | noodle p |
| 070 | JavaScript Node.js | 240928T181603Z | noodle p |
| 091 | C gcc | 240927T131704Z | jdt |
| 099 | Javascript | 240928T025352Z | l4m2 |
| 119 | JavaScript ES2019 | 240928T040419Z | Neil |
| 106 | PHP 7.4+ 109 | 240928T010145Z | Ismael M |
| 073 | Arturo | 240927T150056Z | chunes |
AWK, 91 80 110 79 76 bytes
1~NR{srand()}{for(i=0;i++<NF;)printf"\033[38;5;"int(rand()*99)"m"$i" "}$0=FS
NR<2{srand()} # seed only once (or colors repeat)
{for(i=0;i++<NF;){printf # print each word
"\033[38;5;"int(rand()*99)"m"$i" " # with random color
}}$0=" " # new line
Here's my best attempt:
JavaScript, 97 bytes
Uses deprecated element <font> and deprecated methods.
f=
s=>document.write("<pre>"+s.replace(/\S+/g,m=>m.fontcolor(Math.random().toString(16).slice(-6))))
f("Lorem ipsum dolor sit amet,\n consectetur\tadipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
JavaScript, 123 bytes
This version uses the console. It's a bit longer, but doesn't use deprecated methods/elements. Stack Snippets don't seem to support styled output, so here's a live example.
f=
s=>console.log(s.replace(/\S+/g,"%c$&"),...Array(...s.split(/\s+/)).map(_=>"color:#"+Math.random().toString(16).slice(-6)))
Python 3.8 (pre-release), 113 103 bytes
from random import*
def f(s):print(''.join([c+f'\033[{randint(20,36)}m'*c.isspace()for c in' '+s])[1:])
- 103 bytes thanks @movatica for code
- thanks @jdt for code and ideas and @Jordan for space remark
Typst - 117 bytes
#(a=>{show regex("\\S+"):x=>context{text(oklch(50%,99%,(here().position().x/1pt+datetime.today().day())*9deg),x)};a})
It's a function that accepts a string and returns colored content. As far as I know, the only way to have a different output each time is to use the current date.
Call it like this:
#(a=>{show regex("\\S+"):x=>context{text(oklch(50%,99%,(here().position().x/1pt+datetime.today().day())*9deg),x)};a})(
"Welcome to Code Golf and Coding Challenges Stack Exchange! This is a site for recreational programming competitions, not general programming questions.
Challenges must have an objective scoring criterion, and it is highly recommeded to first post proposed challenges in the Sandbox."
)
Python 3, 97 bytes
Using a lookbehind regexp to insert color codes after whitespace.
import random,re
def f(s):print(re.sub(r'^|(?<=\s)',lambda _:f'\033[{random.randint(20,36)}m',s))
C - 80 75 bytes
b,c;main(){while(read(1,&b,1)){c^=b;printf("␛[38;5;%dm%c",b==32?c:-1,b);}}
To compile locally replace ␛ with an ANSI escape (0x1b)
Ungolfed
#include <stdio.h>
#include <unistd.h>
char buffer,color;
int main(){
while(read(1,&buffer,1)){ // read stdin
color^=buffer; // make color appear random
printf("\e[38;5;%dm%c",buffer==' ' ? color : -1, buffer);
}
}
C#, 136 bytes
string a()=>$"\x1B[38;5;{new Random().Next()%16}m";void f(string s){foreach(var c in a()+s)Console.Write(char.IsWhiteSpace(c)?a()+c:c);}
Explanation
string a()=>$"\x1B[38;5;{new Random().Next()%16}m"; // Generates a randomly colored ANSI escape color code
void f(string s)
{
foreach(var c in a()+s) // For each char c in s, (appending a color code to the start of s)
Console.Write(char.IsWhiteSpace(c)? a()+c : c); // If whitespace, print color code + c, else c
}
Ruby -p, 37 bytes
Contains an unprintable ESC character before the [.
gsub(/\S+/){"[38;5;#{rand 256}m#$&"}
Vyxal Ḣso, 27 bytes
‛ß∵øḂ,‡ȧḃḊƛkṄ℅H`<¨² ÷¥=#Π>Π
Try it Online!
Indirect -3 thanks to l4m2 for reminding me that font tags exist, -2 thanks to lyxal, -1 thanks to pacman256. Add 3 bytes if handling HTML tags is required. See the revision history for a version with a more balanced colour distribution.
This would be a lot simpler (18 bytes) if only handling spaces was required, but oh well.
‛ß∵øḂ, # Output "<pre>" (required because newlines)
‡--Ḋ # Group adjacent items by
ȧ # Does removing whitespace
ḃ # yield an empty string?
ƛ # Over each
℅ # Choose a random integer
kṄ # from 1 to 4096
H # in hexadecimal
`... # Compressed string "<font color=#[color]>[text]"
# s flag concatenates this, o flag outputs it
# and Ḣ flag renders the result as HTML
Japt, 44 40 30 bytes
Making Japt do things it shouldn't be able to do again!
OlUr"%S+"Èimi"␛[38;2;{3ÆLöÃq';
Try it (open your browser's console)
05AB1E, 33 31 29 28 26 bytes
.γð›}ε7Ý39Sδì˜Ω27ç"ÿ[ÿmÿ"?
-4 bytes thanks to @emanresu
Uses the 16 Windows 10 console colors.
Screenshot (which took a while to make, since apparently there was a Windows-10 patch that disabled ANSI again, so I had to enable it (again) in my Registry..):
Try it online (to see the actual ANSI-escaped output).
Explanation:
.γ # Adjacent group-by on the (implicit) input-string:
# (implicitly push the current character)
ð› # Check whether this character is larger than " "
# (aka, not "\t", "\n", nor " ")
}ε # After the group-by: map over each substring:
# (implicitly push the current substring)
7Ý # Push a list in the range [0,7]
39S # Push pair [3,9]
δ # Apply double-vectorized over both lists:
ì # Prepend
˜ # Flatten the [[30,90],[31,93],...,[39,97]] list
Ω # Pop and push a random integer from this list
27ç # Push 27, and convert it to an ASCII character: ␛
"ÿ[ÿmÿ" # Push this string, where:
# - the first `ÿ` is replaced with the ␛
# - the second `ÿ` is replaced with the random integer
# - the third `ÿ` is replaced with the current substring
? # Pop and output it (without newline)
Haskell, 161, 135 bytes
import System.CPUTime
g f=f.(\(%)i->"\ESC["++shows(30+60*i%2+i%9%8)"m")mod<$>getCPUTime
f=(g(++)<*>).foldMap(g. \c i->c:[i|i<-i,c<'!'])
-26 bytes after looking at jdt's solution, and realizing that every space can have a color code attached without breaking the solution.
Wolfram Language (Mathematica), 83 bytes
StringReplace[a:Except[" "|" "|"
"]..:>a~Style~RandomColor[]~ToString~StandardForm]
Returns a string colored in Mathematica's built-in format.
Uiua, 41 38 33 30 bytes
&p⍜⊜□⍚($"\x1b[38;5;_m_"⌈×99⚂)⊸>@
Note the trailing space, and that \x1b should be a literal ESC byte, which is included in the SBCS encoding for Uiua, at least as of 0.13.0-dev-2.
Explanation:
⊸>@ # mask of all characters greater than space
⍜⊜□⍚( # apply to each island of ones:
⌈×99⚂ # random integer between 1 and 99
$"\x1b[38;5;_m_") # Prepend this ANSI color code to the word
&p # print with newline
The ANSI color codes are of the form ESC[38;5;{ID} where ID is a number between 1 and 231 inclusive which correlates to a terminal color. Here, I just used the colors 1 to 99 because it's a byte shorter and we only have to support 16 at a minimum.
Screenshot of the program running:
JavaScript (Node.js), 85 70 bytes
s=>console.log(s.replace(/\S+/g,s=>`␛[38;5;${Math.random()*99|0}m`+s))
The ␛ is used as a placeholder for what should be a raw ESC (0x1B) byte, since Stack Exchange doesn't like to render control characters.
C (gcc), 92 91 bytes
x;f(int*s){for(x=srand(s);*s;x=!s++)printf("\e[38;5;%dm%s",x|isspace(*s)?rand()%256:-1,s);}
-1 byte thanks to ceilingcat!
Javascript, 99 bytes
f=
s=>document.write(`<pre>`+s.replace(/\s|^|(.)/g,(h,c)=>`<font color=${z=c?z:Math.random()*1e6}>`+h))
<textarea id=input1><font color=#123456> test </font></textarea><input type=button onclick=f(input1.value)>
<z>${c} to allow input with <>, later use nop <font> instead
JavaScript (ES2019), 119 bytes
f=
s=>console.log(s.replace(r=/\s*\S+\s*/g,"%c%s"),...s.match(r).flatMap(w=>['color:#'+Math.random().toFixed(3).slice(2),w]))
<input type=button value=Run onclick=f(i.value)><textarea id=i>Test	of
various whitespace</textarea>
Works by logging to the browser's console which should honour tabs and newlines. Colours are random from the selection #000...#999.
PHP 7.4+ - 109 106 bytes
Thanks to Jordan for pointing out that the #RGB format works, and saved me 3 bytes.
An anonymous arrow function that print the HTML containing all the stylized words.
The <pre> is needed to keep the whitespace.
fn($t)=>print('<pre>'.preg_replace_callback('/\S+\s*/',fn($m)=>'<font color=#5'.rand(10,99).">$m[0]",$t))
The idea is simple: randomly generates 89 colors (the minimum required is 16), into a deprecated <font> tag.
I chose to change the green and bçue channels for a decent visual variety in the colors (1 digit for each channel).
Does it's best to keep whitespaces by using the <pre> tag.
As per the rules, HTML output is allowed, and a function is also allowed.
You can try it here:
// This is my code
let answer = "fn($t)=>print('<pre>'.preg_replace_callback('/\\S+\\s*/m',fn($m)=>'<font color=#5'.rand(10,99).\">$m[0]\",$t))";
document.getElementById('code').value = answer;
document.getElementById('code_length').textContent = answer.length;
// Here's the PHP code that will run
let code = `
// Example text
$text = "Write a program or function that takes a string as input and prints or otherwise renders the text with each word in a random color";
// My code
$fn = ${answer};
// Run the code
$fn($text);
`;
run_php(code);
async function run_php(code) {
const { PhpWeb } = await import('https://cdn.jsdelivr.net/npm/php-wasm/PhpWeb.mjs');
const php = new PhpWeb;
let out = '';
php.addEventListener('output', (event) => {
out += event.detail.join('');
});
let x = await php.run('<?php ' + code);
document.getElementById('output_text').value = out;
document.getElementById('output_html').innerHTML = out;
}
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
p {
margin: 0;
}
#code {
width: 100vw;
width: 100dvw;
resize: resize-x;
}
#output_text {
width: 100vw;
width: 100dvw;
height: 50vh;
height: 50dvh;
resize: resize-x;
}
#output_html {
max-width: 100vw;
max-width: 100dvw;
overflow: auto;
}
<p>Code: - Length: <span id="code_length">0</span></p>
<textarea id="code"></textarea>
<p>Output:</p>
<textarea id="output_text"></textarea>
<div id="output_html"></div>
Arturo, 73 bytes
$=>[loop match&{\S+|\s+}=>[prints color to :color map 3=>[255 1random]&]]
Works in the online playground and most terminals.









