25
\$\begingroup\$

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

 

Leaderboard:

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.raw`h\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> 

\$\endgroup\$
4
  • \$\begingroup\$ @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." \$\endgroup\$ Commented Nov 3, 2020 at 21:59
  • \$\begingroup\$ @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. \$\endgroup\$
    – Scott
    Commented Nov 3, 2020 at 22:25
  • \$\begingroup\$ @Scott, caird Thanks! \$\endgroup\$
    – Luis Mendo
    Commented Nov 3, 2020 at 22:54
  • 11
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Commented Nov 4, 2020 at 18:57

40 Answers 40

51
\$\begingroup\$

Haskell, 28 bytes

(`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
\$\endgroup\$
3
  • 33
    \$\begingroup\$ Albedo, how thematically appropriate! \$\endgroup\$
    – xnor
    Commented Nov 3, 2020 at 22:42
  • 1
    \$\begingroup\$ It's too bad there's a c in the second group or a straight comparison would work. Maybe still can be special-cased? \$\endgroup\$
    – xnor
    Commented Nov 3, 2020 at 22:49
  • 1
    \$\begingroup\$ 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) \$\endgroup\$
    – lynn
    Commented Nov 3, 2020 at 22:59
11
\$\begingroup\$

Retina 0.8.2, 7 bytes

A`p
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:

T`L`l`^[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.

\$\endgroup\$
10
\$\begingroup\$

K (oK), 23 19 18 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
\$\endgroup\$
9
\$\begingroup\$

Jelly, 6 bytes

,2ḥ93Ḃ

Try it online!

Uses the Jelly hashing function. 5 might be possible.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I knew there was some way to use , but I'm not familiar enough with it to give it a genuine try. +1 \$\endgroup\$ Commented Nov 4, 2020 at 2:45
  • 2
    \$\begingroup\$ Close, but no cigar: ,Żḥı4 \$\endgroup\$ Commented Nov 5, 2020 at 14:32
8
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

05AB1E, 7 bytes

Takes input in lower case.

CƵl%3%È

Try it online! or Verify all cases!

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?
\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 35 bytes - your turn now... \$\endgroup\$ Commented Nov 4, 2020 at 11:22
  • 1
    \$\begingroup\$ Down to 33 now! :-) \$\endgroup\$ Commented Nov 4, 2020 at 13:04
  • \$\begingroup\$ ping pong... \$\endgroup\$ Commented Nov 4, 2020 at 13:20
5
\$\begingroup\$

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.

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

Jelly, 21 14 12 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
\$\endgroup\$
0
4
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 7 bytes from your Haskell answer \$\endgroup\$ Commented Nov 3, 2020 at 22:35
  • \$\begingroup\$ @cairdcoinheringaahing Thanks! I assume “doable” compresses to the same length, right? \$\endgroup\$
    – lynn
    Commented Nov 3, 2020 at 22:46
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Nov 3, 2020 at 22:49
4
\$\begingroup\$

R, 35 28 27 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'.

\$\endgroup\$
5
  • \$\begingroup\$ 33 bytes; your turn! :-) \$\endgroup\$ Commented Nov 4, 2020 at 12:51
  • 1
    \$\begingroup\$ Can you use c instead of ya? \$\endgroup\$ Commented Nov 4, 2020 at 13:43
  • \$\begingroup\$ Yes! Thankyou very much! \$\endgroup\$ Commented Nov 4, 2020 at 13:44
  • 1
    \$\begingroup\$ Looks like you can remove the ^ \$\endgroup\$ Commented Nov 4, 2020 at 15:33
  • \$\begingroup\$ Thanks! I'm really not concentrating enough, am I? \$\endgroup\$ Commented Nov 4, 2020 at 15:44
3
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ 47 bytes \$\endgroup\$ Commented Nov 3, 2020 at 22:09
  • \$\begingroup\$ @RobinRyder That's worth posting as your own answer! \$\endgroup\$
    – Giuseppe
    Commented Nov 3, 2020 at 22:11
  • \$\begingroup\$ Thanks, but you go ahead - I would never have thought of colors() on my own! \$\endgroup\$ Commented Nov 3, 2020 at 22:19
  • 1
    \$\begingroup\$ @RobinRyder fair enough; you did leave in a c() so I was able to golf it down a bit more :-) \$\endgroup\$
    – Giuseppe
    Commented Nov 3, 2020 at 22:21
  • 1
    \$\begingroup\$ 41 bytes.This one I did post separately. :-) \$\endgroup\$ Commented Nov 3, 2020 at 22:54
3
\$\begingroup\$

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)

\$\endgroup\$
4
  • \$\begingroup\$ 12 bytes \$\endgroup\$ Commented Nov 4, 2020 at 15:57
  • \$\begingroup\$ @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!) \$\endgroup\$ Commented Nov 4, 2020 at 16:06
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Nov 4, 2020 at 16:58
  • \$\begingroup\$ @NahuelFouilleul - perfect, so thanks! \$\endgroup\$ Commented Nov 4, 2020 at 17:43
3
\$\begingroup\$

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))
    (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)
    (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/
// then downloading the resulting wasm file
// then running [...require('fs').readFileSync('path/to/file.wasm')]
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.
// const bytes = require('fs').readFileSync('./output.wasm')

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)))
})()

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 8 bytes with a single string literal and å. \$\endgroup\$
    – ovs
    Commented Dec 9, 2020 at 9:17
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Japt -!, 13 9 8 bytes

g8 k`þ

Try it

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 10 9 bytes

›⁶³﹪⍘Sβ⁹⁴

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:

     S      Input word
    ⍘ β     Decoded as base 26 using lowercase alphabet
   ﹪   ⁹⁴   Modulo literal 94
›⁶³         Check whether 63 is greater than the result
            Implicitly print
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
4
  • 3
    \$\begingroup\$ I think you have to count env variable assignment towards byte count. This is what is usually done with command line options. \$\endgroup\$ Commented Nov 4, 2020 at 10:22
  • \$\begingroup\$ @valsaysReinstateMonica per meta consensus, command line options do not count towards byte count. \$\endgroup\$
    – pxeger
    Commented Nov 4, 2020 at 15:05
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 4, 2020 at 15:44
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – Shaggy
    Commented Nov 6, 2020 at 21:49
2
\$\begingroup\$

Canvas, 12 bytes

{c]∑“N*.[„;%

Try it here!

same method as pxeger's answer.

\$\endgroup\$
2
\$\begingroup\$

Python 3, 71 56 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!

\$\endgroup\$
4
  • \$\begingroup\$ This isn't working... Results from TIO: [1, 1, 1, 1, True, 1, 1, 1, False, 1, 1, 1] \$\endgroup\$
    – Scott
    Commented Nov 3, 2020 at 23:41
  • \$\begingroup\$ Also, in "r o y g b i v".split() can be shortened to in"roygbiv" \$\endgroup\$
    – Scott
    Commented Nov 3, 2020 at 23:43
  • 1
    \$\begingroup\$ @Scott I fixed it \$\endgroup\$
    – aidan0626
    Commented Nov 3, 2020 at 23:59
  • \$\begingroup\$ 44 bytes. I included the golfing steps in the header, feel free to ask if anything is unclear. \$\endgroup\$
    – ovs
    Commented Nov 4, 2020 at 10:34
2
\$\begingroup\$

Ruby -n, 18 bytes

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – ovs
    Commented Nov 4, 2020 at 10:21
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

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)

\$\endgroup\$
2
  • \$\begingroup\$ 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) \$\endgroup\$ Commented Nov 6, 2020 at 20:37
  • \$\begingroup\$ 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! \$\endgroup\$
    – rydwolf
    Commented Nov 6, 2020 at 20:42
2
\$\begingroup\$

Python 3, 38 31 bytes

-7 thanks to DLosc

lambda s:s[-2]in'egou'>'a'<s[1]

Try it online!

Just tests the second and second-to-last characters. Takes a different approach to aidan0626's submission and doesn't rely on custom hash seeds like pxeger's.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ By making the second-to-last character the primary test, you can get 36 bytes, which becomes 31 bytes with some extra golfing. \$\endgroup\$
    – DLosc
    Commented Dec 8, 2021 at 19:28
  • \$\begingroup\$ @DLosc Oh wow, nice find. How does the in'egou'>'a' work? I wouldn't expect the initial bool-to-string comparison to do that. Testing bool-to-string directly says that it's a syntax error, but if it's evaluating to the right first then the in would break... \$\endgroup\$ Commented Dec 8, 2021 at 19:49
  • 2
    \$\begingroup\$ It uses the magic of Python's chaining comparison operators. s[-2]in'egou'>'a'<s[1] is equivalent to s[-2] in 'egou' and 'egou' > 'a' and 'a' < s[1]. See also this Python golfing tip. \$\endgroup\$
    – DLosc
    Commented Dec 8, 2021 at 20:05
2
\$\begingroup\$

Scala, 17 bytes

_.product%237<132

Computes the product of the characters' ASCII values modulo 237 and checks whether the result is smaller than 132. Expects its input in title case.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 22 bytes

Suggested by Andrew Bayly

Returns 0 or 8.

s=>parseInt(s,35)/37&8

Try it online!


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!

\$\endgroup\$
7
  • \$\begingroup\$ Looks like @DominicvanEssen has a better approach for languages with short boolean not operators, thus saving 3 bytes. \$\endgroup\$
    – Neil
    Commented Nov 4, 2020 at 18:46
  • \$\begingroup\$ Could you submit just /d|(?<!pl)e/.test as your answer? \$\endgroup\$ Commented Apr 27, 2022 at 3:32
  • \$\begingroup\$ Nevermind, it loses context of the regex. It would have to be (r=/d|(?<!pl)e/).test.bind(r) which is longer... \$\endgroup\$ Commented Apr 27, 2022 at 3:37
  • 1
    \$\begingroup\$ Since the question asks for truthy/falsey return values, I think the following is valid, and is 1 byte shorter: s=>parseInt(s,36)*6%49%4 \$\endgroup\$ Commented Jul 29 at 8:25
  • 1
    \$\begingroup\$ ... and another byte: s=>parseInt(s,35)/37&8 - this one yields exactly two values - 0 and 8. \$\endgroup\$ Commented Jul 29 at 22:34
1
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 42 bytes \$\endgroup\$
    – gastropner
    Commented Nov 4, 2020 at 5:14
  • \$\begingroup\$ @gastropner Nice one - thanks! :-) \$\endgroup\$
    – Noodle9
    Commented Nov 4, 2020 at 18:58
  • \$\begingroup\$ 41 bytes (removed one unnecessary &) \$\endgroup\$ Commented Nov 6, 2020 at 20:40
  • \$\begingroup\$ @Samathingamajig Well done - thanks! :-) \$\endgroup\$
    – Noodle9
    Commented Nov 6, 2020 at 21:24
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice golfing! You can get 17 bytes using > instead of !=, I think... \$\endgroup\$ Commented Dec 7, 2020 at 11:01
  • 1
    \$\begingroup\$ ...and 16 bytes with * instead of &&... \$\endgroup\$ Commented Dec 7, 2020 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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