# Is It A Rainbow Color?

## Challenge:

The challenge is to determine whether or not a color, given it's name, is one of the colors in the rainbow.

When supplied with a color, your program should output a truthy value if it is a color in the rainbow, and a falsy one otherwise.

## Rules:

1. The possible input options are exhaustive, and defined in the test cases. You can assume that you will not receive any other input than the ones defined
2. Character casing for inputs can be one of: UPPER, lower, or Title Case, but must be consistent
3. Standard loopholes not allowed

## Test Cases:

Truthy:

• red
• orange
• yellow
• green
• blue
• indigo
• violet

Falsy:

• purple
• brown
• pink
• cyan
• maroon

var QUESTION_ID=214678;
var OVERRIDE_USER=97730;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.rawh\d,e=String.raw\-?\d+\.?\d*,f=String.raw[^\n<>]*,g=String.raw<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>,h=String.raw[^\n\d<>]*,j=String.raw<[^\n<>]+>;return new RegExp(String.raw<${d}>+String.raw\s*([^\n,]*[^\s,]),.*?+String.raw(${e})+String.raw(?=+String.raw${h}+String.raw(?:(?:${g}|${j})${h})*+String.raw</${d}>+String.raw))}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

• @LuisMendo "The possible input options is exhaustive, and defined in the test cases. You can assume that you will not receive any other input than the ones define." – caird coinheringaahing Nov 3 '20 at 21:59
• @LuisMendo The answerer can choose a casing, and all inputs will be received in that form. The solution does not need to cater for all. – Scott Nov 3 '20 at 22:25
• @Scott, caird Thanks! – Luis Mendo Nov 3 '20 at 22:54
• I like how you chose colors where looking at the letter at any one index isn't enough to tell if it's in the rainbow or not, and same for indexing from the end. – xnor Nov 4 '20 at 18:57

(elem"albedo").(!!8).cycle


Try it online!

If we wrap the input and index at position 8, the rainbow colors all yield a letter among "albedo", but the non-rainbow colors do not (they yield a letter among "rwpc").

redredre d red
orangeor a nge
yellowye l low
greengre e ngr
blueblue b lue
indigoin d igo
violetvi o let

purplepu r ple
brownbro w nbr
pinkpink p ink
cyancyan c yan
maroonma r oon

• Albedo, how thematically appropriate! – xnor Nov 3 '20 at 22:42
• It's too bad there's a c in the second group or a straight comparison would work. Maybe still can be special-cased? – xnor Nov 3 '20 at 22:49
• I hope it doesn't work out and I can keep the answer thematic :) (I looked a little and didn't find a good way immediately) – Lynn Nov 3 '20 at 22:59

# Retina 0.8.2, 7 bytes

Ap
d|e


Try it online! Link includes test cases. Assumes input in lower case. Outputs non-zero for rainbow colours, zero for the other inputs. Explanation: Simply checks that the colour contains the letters d or e but not p.

64-byte version to check against the 21 specific cases of rainbow colours in three different capitalisations:

TLl^[A-Z]+$|^. ^(red|orange|yellow|green|blue|indigo|violet)$


Try it online! Link includes test cases. Explanation: Either an uppercase input or the leading character is lowercased, after which the exact colours are matched.

# K (oK), 231918 12 bytes

^"rwpc"?*|9#


Try it online!

Assumes input in lower case; based off of a flipped version of @Lynn's Haskell answer.

• 9# repeating-take 9 characters of the input, e.g. "purplepur"
• *| first-reverse, i.e. last
• "rwpc"? lookup character in the string "rwpc", returning either the index of the match, or a null if not present
• ^ check if null, i.e. convert nulls to 1 and actual indices to 0

# Jelly, 6 bytes

,2ḥ93Ḃ


Try it online!

Uses the Jelly hashing function. 5 might be possible.

• I knew there was some way to use ḥ, but I'm not familiar enough with it to give it a genuine try. +1 – caird coinheringaahing Nov 4 '20 at 2:45
• Close, but no cigar: ,Żḥı4 – Jonathan Allan Nov 5 '20 at 14:32

# 05AB1E, 7 bytes

Takes input in lower case.

CƵl%3%È


C converts the color from binary. This allows digits higher than 1, where upper case characters are 10 to 35 and lower case 36 to 61:

C("red") = "r"*2**2 + "e"*2**1 + "d"*2**0 = 53*4 + 40*2 + 39 = 331


Ƶl is the compressed integer 148, the code computes

is C(color)%148%3 Èven?


# R, 41 33 bytes

sd(utf8ToInt(scan(,"")))%%.195<.1


Try it online!

Less elegant than Giuseppe's solution, but 3 11 bytes shorter.

Converts the (lowercase) input to ASCII codepoints, takes the standard deviation of the resulting integers, then takes that modulo 0.195 (found by a grid search). The result is less than 0.1 iff the input is truthy.

# C (gcc), 22 21 bytes

f(int*s){s=*s/203&1;}


Try it online!

Inspired by ErikF's answer. I wrote a little program to brute-force the constants.

# Python 2, 22 bytes

lambda s:hash(s)%683%2


Try it online!

-1 thanks to ovs, who used the extra degree of freedom afforded by the flexible input casing to save a byte.

• %683%2 works with uppercase input: tio.run/… – ovs Nov 3 '20 at 22:49
• @ovs Nice! I hadn't considered varying the input casing to allow for a shorter modulo chain. – Sisyphus Nov 4 '20 at 2:04

# R, 352827 26 bytes

Edit: -1 byte thanks to Dom Hastings, and -1 byte thanks to caird coinheringaahing

!grepl("ro|p|c",scan(,''))


Try it online!

Regular-expression check.
'maroon' + 'brown' both contain 'ro', 'purple' and 'pink' both contain 'p', and 'cyan' contains 'c'.

• 33 bytes; your turn! :-) – Robin Ryder Nov 4 '20 at 12:51
• Can you use c instead of ya? – Dom Hastings Nov 4 '20 at 13:43
• Yes! Thankyou very much! – Dominic van Essen Nov 4 '20 at 13:44
• Looks like you can remove the ^ – caird coinheringaahing Nov 4 '20 at 15:33
• Thanks! I'm really not concentrating enough, am I? – Dominic van Essen Nov 4 '20 at 15:44

# Jelly, 211412 10 bytes

“dʋ»e€µṪ<Ẹ


Try it online!

Takes input in lowercase. Adaption of Neil's method

Golfs:

## How it works

“dʋ»e€µṪ<Ẹ - Main link. Takes S on the left
“dʋ»       - Compressed string; Yield "dep"
€     - For each character in "dep":
e      -   Is it in S?
µ    - Use this triplet as the new argument
Ṫ   - Take the final element (1 if p is present, else 0)
Ẹ - Are either "d" or "e" in S?
<  - The tail is 0 and either "d" or "e" are in S


# Jelly, 8 7 bytes

9ịe“\Ṙ»


Try it online!

Get the ninth character (wrapping) and check if it's in the compressed string “\Ṙ» = “albedo”.

Port of my Haskell answer. caird saved a byte: the coincidence that albedo is an English word actually wins bytes over 9ịe“albedo or 9ịḟ“rwpc, owing to Jelly's compression dictionary.

• @cairdcoinheringaahing Thanks! I assume “doable” compresses to the same length, right? – Lynn Nov 3 '20 at 22:46
• Tbh I‘m not sure. I just tested “albedo“ for a baseline for testing other permutations and was very surprised when it came out as only 2 (or 4 counting delimiters) bytes – caird coinheringaahing Nov 3 '20 at 22:49

# Perl 5, 13 12 bytes

Edit: -1 byte by returning null string as falsy, thanks to Nahuel Fouilleul

$_=!/ro|p|c/  Try it online! Same approach as my R answer (with help from Dom Hastings + Caird Coinheringaahing), but probably better suited to [Perl]... (Edit: realized that porting Neil's Retina answer is actually shorter at also only now slightly longer at 13 bytes) • 12 bytes – Nahuel Fouilleul Nov 4 '20 at 15:57 • @NahuelFouilleul - I wasn't sure whether 'no output' counted as 'falsy' - is that the case? (in which case, thanks very much for the saved byte!) – Dominic van Essen Nov 4 '20 at 16:06 • didn't find a specific topic on golf meta, but perl uses null string as falsey value, otherwise i've already used it on other questions – Nahuel Fouilleul Nov 4 '20 at 16:58 • @NahuelFouilleul - perfect, so thanks! – Dominic van Essen Nov 4 '20 at 17:43 # Pyth, 9 bytes %%Cz283 2  Try it online! Answering my own question now that others have me beat... (FYI I solved this after posting) Explanation: 1. Converts to int with base 256 2. Modulo that by 283 3. Modulo by 2. 1 if rainbow color, 0 if not. # Japt-!, 139 8 bytes g8 kÃ¾  Try it # Charcoal, 10 9 bytes ›⁶³﹪⍘Ｓβ⁹⁴  Try it online! Link is to verbose version of code. Takes input in lower case. Output is a Charcoal boolean, i.e. - if rainbow, nothing if not. Explanation:  Ｓ Input word ⍘ β Decoded as base 26 using lowercase alphabet ﹪ ⁹⁴ Modulo literal 94 ›⁶³ Check whether 63 is greater than the result Implicitly print  # Python 3, 7156 44 bytes -15 bytes thanks to @Scott -12 bytes thanks to @ovs lambda s:(s[0]<'c'<'r'==s[1])==(s[0]in'pcm')  Try it online! • This isn't working... Results from TIO: [1, 1, 1, 1, True, 1, 1, 1, False, 1, 1, 1] – Scott Nov 3 '20 at 23:41 • Also, in "r o y g b i v".split() can be shortened to in"roygbiv" – Scott Nov 3 '20 at 23:43 • @Scott I fixed it – aidan0626 Nov 3 '20 at 23:59 • 44 bytes. I included the golfing steps in the header, feel free to ask if anything is unclear. – ovs Nov 4 '20 at 10:34 # R, 60 44 bytes !scan(,"")%in%colors()[c(547,32,536,68,455)]  Try it online! -13 thanks to Robin Ryder. Takes input as all lowercase. Checks to see if the color is not one of the excluded colors. Outgolfed by Robin Ryder and Dominic van Essen. • 47 bytes – Robin Ryder Nov 3 '20 at 22:09 • @RobinRyder That's worth posting as your own answer! – Giuseppe Nov 3 '20 at 22:11 • Thanks, but you go ahead - I would never have thought of colors() on my own! – Robin Ryder Nov 3 '20 at 22:19 • @RobinRyder fair enough; you did leave in a c() so I was able to golf it down a bit more :-) – Giuseppe Nov 3 '20 at 22:21 • 41 bytes.This one I did post separately. :-) – Robin Ryder Nov 3 '20 at 22:54 # C (gcc), 34 bytes Function takes a lowercase colour and returns 1 if it is rainbow colour, otherwise 0. To save space, I hash the first four characters of the colour with modulo 81 (the first number that didn't have collisions and had all printable remainders) and search for that in the list of hashes for the non-rainbow colours. If there is no match, then it is a rainbow colour. f(int*s){s=!index("D@M1&",*s%81);}  Try it online! I could save two bytes if returning 0 for a rainbow colour and non-zero for a non-rainbow was allowed: f(int*s){!index("D@M1&",*s%81);}  Try it online! # JavaScript (ES6), 20 bytes s=>!/ro|p|c/.test(s)  Try it online! How it works: Get a truthy value if ro is present, p is present, or c is present, then inverts that value so if they are present, the result is falsey, otherwise the result is truthy Look at the regex here (Regex101.com) # JavaScript (ES6), 22 bytes s=>!/p|[^e]n$/.test(s)


Try it online!

How it works: Get a truthy value if it starts with p or ends in n without an e before it. The ! inverts that value so it returns true if no match and false if there is a match. I've tried multiple other regex's that end up being the same length, so i went with this one since it's easy enough to explain.

Look at the Regex here (Regex101.com)

• It looks kind of like I copied this answer by Dominic van Essen, but I didn't even see that answer before submitting this one (especially since the regex is in the same order) – Samathingamajig Nov 6 '20 at 20:37
• It's a different language so it's fine, you'll see a lot of answers ported from others. Welcome to the site, by the way! – Redwolf Programs Nov 6 '20 at 20:42

## WebAssembly Text Format, 111 bytes

(func(result i32)i32.const 0 i32.load i32.const 8 i32.load i32.add i32.const 13 i32.rem_s i32.const 7 i32.le_s)


This function operates on an integer memory array, that should start pre-filled with the chosen color (in Title Case) as a list of ascii code points. (strings can't be provided as normal function arguments in webassembly). The function will return 1 if its a rainbow color, or 0 if its not.

The actual logic behind the function is effectively the following: return (mem[0] + mem[8]) % 13 <= 7. (each character of the color takes 4 bytes in the memory array so byte-index 8 refers to a character-index 2). The actual WebAssembly Text Format is designed to feel like a stack machine, so instructions like i32.const 8 puts an 8 onto the stack while i32.add will take two items off the stack, add them, and put the result back on.

The following is a complete WebAssembly file with the above function embedded inside.

(module
(import "api" "mem" (memory 1))
(export "check" (func 0))
)


This can be compiled to a WebAssembly binary (a binary wasm file can be generated and downloaded through online wat to wasm conversion tools like this one).

The following javascript runs the compiled binary. It contains the logic to create the memory array, pre-filled with a color. For convenience, it has the binary WebAssembly embedded in it.

// Byte array generated by putting the WAT text into https://mbebenita.github.io/WasmExplorer/
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,2,140,128,128,128,0,1,3,97,112,105,3,109,101,109,2,0,1,3,130,128,128,128,0,1,0,6,129,128,128,128,0,0,7,137,128,128,128,0,1,5,99,104,101,99,107,0,0,10,153,128,128,128,0,1,147,128,128,128,0,0,65,0,40,2,0,65,8,40,2,0,106,65,13,111,65,7,76,11])
// Alternativly, you can read from the raw wasm file after generating it.

async function initWaModule() {
const mem = new WebAssembly.Memory({initial:1})
const { instance } = await WebAssembly.instantiate(bytes, { api: {mem}, })

return {
isRainbowColor(color) {
// Insert color param into memory
const i32Array = new Uint32Array(mem.buffer);
i32Array.fill(0)
const colorAsCodePoints = [...color].map(c => c.charCodeAt(0))
i32Array.set(colorAsCodePoints)

// Run webassembly function
return !!instance.exports.check()
}
}
}

const TRUE_COLORS = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
const FALSE_COLORS = ['Purple', 'Brown', 'Pink', 'Cyan', 'Maroon']

;(async () => {
const { isRainbowColor } = await initWaModule()
console.log('These should be true')
TRUE_COLORS.forEach(color => console.log(color, isRainbowColor(color)))
console.log('These should be false')
FALSE_COLORS.forEach(color => console.log(color, isRainbowColor(color)))
})()

# 05AB1E, 14 8 bytes

-6 bytes thanks to @ovs.

'•³€å¤-à


Try it online!

'•³€å¤-à  # full program
-   # subtract...
¤    # last element of...
å     # is...
€      # each character of...
# implicit input...
å     # in...
'•³       # "deep"...
-  # from...
# (implicit) each element of...
å     # is...
€      # each character of...
# implicit input...
å     # in...
'•³       # "deep"
à  # greatest element of list
# implicit output

• 8 bytes with a single string literal and å. – ovs Dec 9 '20 at 9:17

# JavaScript (ES9), 23 bytes

Similar to Neil's Retina answer, but with a negative lookbehind to prevent purple from being matched.

s=>/d|(?<!pl)e/.test(s)


Try it online!

# JavaScript (ES6), 25 bytes

The case doesn't matter. Returns a Boolean value.

s=>parseInt(s,35)%385%3>1


Try it online!

• Looks like @DominicvanEssen has a better approach for languages with short boolean not operators, thus saving 3 bytes. – Neil Nov 4 '20 at 18:46

# Python 3.8 (pre-release)PYTHONHASHSEED=2537, 18 bytes

lambda x:hash(x)%2


Try it online!

I'm pretty sure this is allowed. An environment variable is just like a command-line option, so this is considered a separate programming language to normal Python. Input in lowercase, outputs 1 or 0.

• I think you have to count env variable assignment towards byte count. This is what is usually done with command line options. – val is still with Monica Nov 4 '20 at 10:22
• @valsaysReinstateMonica per meta consensus, command line options do not count towards byte count. – pxeger Nov 4 '20 at 15:05
• Yet I can't make single-byte program in C while passing its actual body using -D argument to compiler. And if you consider it a different language, this becomes borderline close to creating a language for specific challenge after it was posted. – val is still with Monica Nov 4 '20 at 15:44
• Hmm ... this feels a little "cheaty" to me as the seed is doing a lot of the heavy lifting. I would say this should be +4 for the 2537 but I'd suggest taking it to Meta so we can get a consensus on how to handle and score these options. – Shaggy Nov 6 '20 at 21:49

# Canvas, 12 bytes

｛ｃ］∑“Ｎ＊.［„；％


Try it here!

p 255969480%$_.sum  Try it online! Input in Title Case, output is either a truthy integer or falsey zero. $$\255969480\$$ is the lowest common multiple of the sums of all of the Title Cased truthy strings, which is also not a multiple of any of the sums of the Title Cased falsey strings. The reason I use Title Case is because the sums share a lot of common factors, reducing the length of the number. This could definitely be ported to various golfing languages to save lots of bytes, which I might do. see below! # 05AB1E, 14 10 bytes ÇO•F;_â•s%  Try it online! Same method as the above - input in Title Case, output as either 0 for false or a positive integer for true • 05AB1E has builtins for compressing integers in base-255, which are explained in this tip by Kevin. With this ""f41c8c8"H" can be written as •F;_â• for 10 bytes. – ovs Nov 4 '20 at 10:21 # C (gcc), 46 42 41 bytes Saved 4 bytes thanks to gastropner!!! Saved a byte thanks to Samathingamajig!!! f(char*s){s=*s-80&&*s-77&&*s-67&s[3]-87;}  Try it online! Inputs the colour all in caps and return $$\1\$$ for a colour of the rainbow or $$\0\$$ otherwise. • 42 bytes – gastropner Nov 4 '20 at 5:14 • @gastropner Nice one - thanks! :-) – Noodle9 Nov 4 '20 at 18:58 • 41 bytes (removed one unnecessary &) – Samathingamajig Nov 6 '20 at 20:40 • @Samathingamajig Well done - thanks! :-) – Noodle9 Nov 6 '20 at 21:24 # x86 machine code, 8 bytes Hexdump: 6b 01 e7 c1 e8 0a d6 c3  Multiplies the 32-bit value at string start by -25, and extracts bit 9 from the result. Returns al = -1 for rainbow colours, and al = 0 for non-standard ones. Disassembly: 6B 01 E7 imul eax,dword ptr [ecx],0FFFFFFE7h C1 E8 0A shr eax,0Ah ?? ?? ?? C3 ret  Here, ?? ?? represents the "undocumented" SALC instruction. # GAWK, 18 16 bytes (-2 thanks to Dominic van Essen) 2>$0=/[de]/*!/p/


Try it online!

Translation of Neil's has "d" or "e" but not "p" logic. Uses "2>" to make sure the condition is always true for any input, and sets $0 to truthy/falsey so that the default action, which is print$0, will output the result.

• Nice golfing! You can get 17 bytes using > instead of !=, I think... – Dominic van Essen Dec 7 '20 at 11:01
• ...and 16 bytes with * instead of &&... – Dominic van Essen Dec 7 '20 at 11:02

# 05AB1E, 16 bytes

.•4W'bÓ´€‚Γ•I2£å
`

Try it online!

This uses the fact that there is a fixed set of possible inputs.