21
\$\begingroup\$

Challenge

Consider the rainbow as seven colours, represented by strings as Red Orange Yellow Green Blue Indigo Violet.
Your task is to create a program that receives one of these colours as input and outputs next in order rainbow colour. This includes overlapping Violet -> Red

Input

A string containing one of rainbow colours.

Output

The next in order colour of the rainbow.

Rules

  • Colour names are case sensitive. They must match the case included in this post.
  • The input will always be valid. Any behavior is allowed for invalid input.
  • This is code golf, so the shortest amount of bytes wins!

Example Input and Output

Input -> Output
Red -> Orange
Orange -> Yellow
Yellow -> Green
Green -> Blue
Blue -> Indigo
Indigo -> Violet
Violet -> Red
\$\endgroup\$
8
  • 1
    \$\begingroup\$ "Provide at least one example input and output. Make sure they match your own description of what the input should look like." Are you describing your own challenge post? Or is this a requirement for solutions? \$\endgroup\$
    – recursive
    Mar 21, 2018 at 6:52
  • 6
    \$\begingroup\$ Are lower case colours okay? \$\endgroup\$
    – Emigna
    Mar 21, 2018 at 8:32
  • 4
    \$\begingroup\$ But what happens when you reach 'gray'? ;) \$\endgroup\$
    – AJFaraday
    Mar 21, 2018 at 11:24
  • 1
    \$\begingroup\$ @Emigna From the way OP phrased the question, I would guess that you can choose whether to do upper case, lower case, or case insensitive. Provide at least one example input and output. Make sure they match your own description of what the input should look like. \$\endgroup\$
    – sonrad10
    Mar 21, 2018 at 13:47
  • 1
    \$\begingroup\$ Are trailing spaces okay? \$\endgroup\$
    – ivzem
    Mar 22, 2018 at 17:45

42 Answers 42

22
\$\begingroup\$

JavaScript, 68 bytes

s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]

For input "Red", this function first construct an RegExp /Red(.[a-z]*)/ to match the string 'RedOrangeYellowGreenBlueIndigoVioletRed' and then return the first capture result.

f=
s=>'RedOrangeYellowGreenBlueIndigoVioletRed'.match(s+'(.[a-z]*)')[1]

document.write('<table><tr><th>Input<th>Output')
for(i='Red';;){
document.write(`<tr><td>${i}<td>${i=f(i)}`);
if(i=='Red')break;
}

\$\endgroup\$
3
  • \$\begingroup\$ What's the result for input "Violet"? I guess you should change the text to 'RedOrangeYellowGreenBlueIndigoVioletRed' or something \$\endgroup\$ Mar 21, 2018 at 8:38
  • 1
    \$\begingroup\$ @OlivierGrégoire Ok, added. This rule is changed by OP after answer posted. \$\endgroup\$
    – tsh
    Mar 21, 2018 at 8:42
  • \$\begingroup\$ I didn't know: I only saw the final version of the question. \$\endgroup\$ Mar 21, 2018 at 8:59
9
\$\begingroup\$

Perl 5 -p, 58 57 bytes

#!/usr/bin/perl -p
$_={(Red,Orange,Yellow,Green,Blue,Indigo,Violet)x2}->{$_}

Try it online!

Now that the challenge has been changed to be cyclic the regex solution

say RedOrangeYellowGreenBlueIndigoVioletRed=~/$_(.[a-z]+)/

isn't optimal anymore (due to the double Red)

Also 57 bytes:

#!/usr/bin/perl -p
$_=(Indigo,Blue,Violet,Yellow,Orange,Red,Green)[ord>>2&7]

Try it online!

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

Python, 79 bytes

z="Red Orange Yellow Green Blue Indigo Violet".split()*2
dict(zip(z,z[1:])).get

Try it online!

Handles Violet -> Red. The desired function is given anonymously in the second line.


80 bytes

lambda x:"Red Orange Yellow Green Blue Indigo Violet Red".split(x)[1].split()[0]

Try it online!

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

Perl 6, 56 bytes

{<Indigo Blue Violet Yellow Orange Red Green>[.ord/4%8]}

Try it online!

Exploits the fact that bits 2-4 of the ASCII codes of each color's first letter happen to map to 0-6.

say map (*.ord +> 2) % 8, <R O Y G B I V>
# (4 3 6 1 0 2 5)

Here's a nice non-competing solution that uses "purple" instead of "indigo" and "violet" (38 chars, 59 bytes):

{'🍎🧡💛💚💙💜🍎'.uninames~~m/$^a.\S+.<(\S+/}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Almighty Unicode names \$\endgroup\$ Mar 21, 2018 at 14:54
  • \$\begingroup\$ As interesting as this solution is, it ultimately doesn't follow the spec. Could you include a compliant version in you answer and post this as an addendum? \$\endgroup\$
    – Dennis
    Mar 21, 2018 at 15:01
  • \$\begingroup\$ There is also a %12 solution for Coconut, but of course this is neater. \$\endgroup\$ Mar 21, 2018 at 18:44
5
\$\begingroup\$

Ruby -n, 62 60 bytes

-2 by Asone Tuhid.

p"RedVioletIndigoBlueGreenYellowOrangeRed"[/.[a-z]+(?=#$_)/]

Try it online!

Regex approach looks promising for Ruby too. However, I arrived at a shorter solution using a lookahead and directly printing the match, rather than playing with capturing groups. The list of colors is in reverse direction since lookahead is 1 byte cheaper than lookbehind.

\$\endgroup\$
1
  • \$\begingroup\$ very nice, -2 bytes (/#$_/ interpolates) \$\endgroup\$ Mar 21, 2018 at 12:56
4
\$\begingroup\$

Red, 87 bytes

func[c][print first find/tail[Red Orange Yellow Green Blue Indigo Violet Red]to-word c]

Try it online!

\$\endgroup\$
2
  • 4
    \$\begingroup\$ No idea what this language is, whether or how your code works, or whether it's golfed at all, but have a +1 just for using a language called "Red" for this challenge. \$\endgroup\$
    – msh210
    Mar 21, 2018 at 12:50
  • \$\begingroup\$ @ msh210 It's closely related to Rebol ( Relative Expression-Based Object Language). The language represents code, data and metadata in the same manner - with blocks denoted by []. The current Red distribution is only 1.1 MB and includes a console/interpeter, as well as compiler that can cross-complie to different platforms. My code is golfed in the sence that I tried different solutions and removed all the spaces I can. The bad thing is that the space is the delimiter almost everywhere. All math expressions need to have spaces on both sides of the operators like a: b + c (a=b+c). \$\endgroup\$ Mar 21, 2018 at 13:10
4
\$\begingroup\$

05AB1E, 30 bytes

“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“#™DIk>è

Try it online!

Explanation

“†¾›ÈŠÛˆ¨‡—ëßigo°Íolet“          # push a string of colours
                       #         # split on spaces
                        ™        # title-case each
                         D       # duplicate
                          Ik     # get the index of the input
                            >    # increment
                             è   # get the element at that index
\$\endgroup\$
3
\$\begingroup\$

Excel, 85 bytes

=CHOOSE(MOD(CODE(A1),12),"green","indigo","yellow",,,"orange","blue",,"violet","red")

Uses lowercase names.

Same approach, with Uppercase letters 86 bytes:

=CHOOSE(MOD(CODE(A1),12),"Violet","Red",,,"Green","Indigo","Yellow",,,"Orange","Blue")
\$\endgroup\$
3
\$\begingroup\$

Haskell, 80 71 75 bytes

Thanks to Laikoni for shortening 9 bytes!

g x=snd(span(/=x)$words"Red Orange Yellow Green Blue Indigo Violet Red")!!1

Try it online!


Another solution, slightly more idiomatic, but I could not get it shorter:

data R=Red|Orange|Yellow|Green|Blue|Indigo|Violet deriving(Enum,Read,Eq)
succ.read

It needs to derive Read because of the requirement that the input is a string and at least Eq or Show in order to either test for equality or show the result.

\$\endgroup\$
5
  • \$\begingroup\$ 71 bytes with span: Try it online! \$\endgroup\$
    – Laikoni
    Mar 21, 2018 at 8:00
  • \$\begingroup\$ @Laikoni Wow, that's cool, thanks! I forgot about span... \$\endgroup\$ Mar 21, 2018 at 8:04
  • 1
    \$\begingroup\$ OP clarified that Violet should wrap around to Red, so you need to add Red again to the end of the string. \$\endgroup\$
    – Laikoni
    Mar 21, 2018 at 11:06
  • \$\begingroup\$ I like the idea of the second one a lot! However succ Violet won't work for Enums don't wrap around :( \$\endgroup\$ Mar 21, 2018 at 12:22
  • \$\begingroup\$ @BMO Exactly. When I made that version I wasn't aware of the wrap-around requirement. \$\endgroup\$ Mar 21, 2018 at 12:35
3
\$\begingroup\$

Retina, 65 58 bytes

$
(.[a-z]+)
L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1

Try it online!

Explanation

$
(.[a-z]+)

We start by appending (.[a-z]+) to the input, thereby turning it into a regex which matches the input colour, immediately followed by exactly one more colour (capturing the latter).

L$:`RedOrangeYellowGreenBlueIndigoVioletRed
$1

Now the : swaps the stage's input with its own regex. So the previous result becomes the regex and it's matched against the list of colours. The (single) match gets replaced with its first capturing group (i.e. the next colour in the cycle) and returned. Output at the end of the program happens automatically.

\$\endgroup\$
4
  • \$\begingroup\$ Here is another 65-byte alternative. \$\endgroup\$ Mar 21, 2018 at 12:14
  • \$\begingroup\$ Yeah, I removed my comment after seeing Kevin's solution. Having to set up \1 and jumping to the target wastes many bytes ::-) \$\endgroup\$
    – Ton Hospel
    Mar 21, 2018 at 13:15
  • \$\begingroup\$ @TonHospel found something. :) \$\endgroup\$ Mar 21, 2018 at 13:17
  • 1
    \$\begingroup\$ @KevinCruijssen Thanks to your and Ton's pushing for a no-delimiter solution, I ended up finding a 58-byter. ;) \$\endgroup\$ Mar 21, 2018 at 13:21
3
\$\begingroup\$

Vim, 59 56 53 52 Bytes

-1 byte thanks to tsh

2IYellow Green Blue Indigo Violet Red Orange <Esc>*wywVp
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 2IYellow Green Blue Indigo Violet Red Orange <Esc>*wywVp \$\endgroup\$
    – tsh
    Mar 21, 2018 at 12:14
3
\$\begingroup\$

Java (JDK 10), 77 bytes

s->"Red Orange Yellow Green Blue Indigo Violet Red".split(s)[1].split(" ")[1]

Try it online!

Credits

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

SOGL V0.12, 23 bytes

k‰³d∆|ΝμHō↑≥░δ÷f‘θ⁽,WIw

Try it Here!

Explanation:

...‘θ⁽,WIw  
...‘        push "red orange yellow green blue indigo violet"
    θ       split on spaces
     ⁽      uppercase the 1st letter of every item (SOGLs dictionary only has lowercase words)
      ,W    get the inputs index in the array
        I   increment
         w  and get that item in the array, wrapping if necessary
\$\endgroup\$
2
\$\begingroup\$

Coconut, 79 bytes

s->"# Violet Red # # Green Indigo Yellow # # Orange Blue".split()[ord(s[0])%12]

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Don't know Coconut. But think you should be able to cut 2 bytes by using lowercase letters, as this reduces the max modulo value: s->"# green indigo yellow # # orange blue # violet red".split()[ord(s[0])%12] \$\endgroup\$
    – Wernisch
    Mar 21, 2018 at 12:46
  • \$\begingroup\$ @Wernisch Thanks for the suggestion. Though I'll wait until OP has responded whether lowercase letters are acceptable before updating. \$\endgroup\$
    – Laikoni
    Mar 21, 2018 at 13:09
2
\$\begingroup\$

Husk, 28 bytes

S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉

Try it online!

Maybe there are better options for managing the arguments, but this is the best I could find

Explanation

S!o→€⁰w¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉
       ¨ṙ}ΘΞĠ«ẇ₇G²€ḃλBżḃIÿö⌉    Compressed string with all the colors
                                "Red Orange Yellow Green Blue Indigo Violet"
      w                         Split on spaces
S                               Pass the list to both the following functions:
    €⁰                          1) Find the index of the input in the list
  o→                                  and increase it by one
 !                              2) Get the element of the list at the
                                   resulting position (indexing is cyclical)
\$\endgroup\$
2
\$\begingroup\$

Stax, 31 30 29 bytes

ÇôF┘≡▓ƒ◄╙>┘☼░⌂╪B<U[ÇQ╒eöΣQ╔÷n

Run and debug it

This uses the ring translation instruction. It replaces each element in an array with the following one from the "decoder ring". Usually, it's used to do character replacement in a string, but it can be used on an entire string too, if it's wrapped in a singleton array.

Here's the unpacked, ungolfed, commented ascii representation of the same program.

]   wrap input in singleton array
`5^bZ_9G*h]h%oM~X9e-0ZQJkb2`    compressed string literal with color names
:.j title case and split on spaces
:t  do ring translation

Run this one

\$\endgroup\$
6
  • \$\begingroup\$ ok... I love these languages =) \$\endgroup\$
    – lolad
    Mar 21, 2018 at 8:16
  • 3
    \$\begingroup\$ Fails for Violet -> Red \$\endgroup\$ Mar 21, 2018 at 12:19
  • 1
    \$\begingroup\$ @WeijunZhou: That test case was added after this submission. \$\endgroup\$
    – recursive
    Mar 21, 2018 at 14:26
  • 1
    \$\begingroup\$ @WeijunZhou: I fixed that test case and shaved a byte. \$\endgroup\$
    – recursive
    Mar 22, 2018 at 4:05
  • 1
    \$\begingroup\$ @WeijunZhou: It seems to be an inconsistency between the C# and JS implementations of stax. I'll add a test case and normalize the behavior for the next release. \$\endgroup\$
    – recursive
    Mar 22, 2018 at 5:58
2
\$\begingroup\$

J, 67 64 62 bytes

-2 bytes thank to FrownyFrog

>:&.((cut'Red Orange Yellow Green Blue Indigo Violet Red')i.<)

Try it online!

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

R, 109 93 bytes

function(x){y=c("Red","Orange","Yellow","Green","Blue","Indigo","Violet");y[match(x,y)%%7+1]}

Try it online!

-16 thanks to Giuseppe for the use of match advice

\$\endgroup\$
8
  • \$\begingroup\$ welcome to PPCG! this is a nice first answer. I think match(y,x)%%7+1 is shorter for indexing than your if statement. Additionally, the builtin colors() contains a lot of color names, if you find the indices :) \$\endgroup\$
    – Giuseppe
    Mar 22, 2018 at 18:33
  • \$\begingroup\$ oops, looks like colors() doesn't contain indigo! Ah well, still, +1! \$\endgroup\$
    – Giuseppe
    Mar 22, 2018 at 18:38
  • \$\begingroup\$ thanks! match is better here \$\endgroup\$
    – DS_UNI
    Mar 23, 2018 at 14:02
  • \$\begingroup\$ 91 bytes \$\endgroup\$
    – Giuseppe
    Mar 23, 2018 at 14:04
  • \$\begingroup\$ and yeah I first tried to use colors() :/ \$\endgroup\$
    – DS_UNI
    Mar 23, 2018 at 14:04
1
\$\begingroup\$

Batch, 97 bytes

@set s=Red Orange Yellow Green Blue Indigo Violet Red
@call set s=%%s:*%1 =%%
@echo %s: =&rem %

Explanation: The call on the second line has the effect of substituting the parameter into the command and evaluating it, turning it into e.g. set s=%s:Red =%, which deletes the prefix of the string that includes the parameter. The substitution on the third line then replaces all the spaces with statement separators and comments. This works because string substitution happens before parsing.

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

Ruby -n, 75 69 bytes

a=%w{Red Orange Yellow Green Blue Indigo Violet};p a[-~(a.index$_)%7]

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Why the i&& thing? No need to check for nil, as “Ignore any errors if this is not a colour.” \$\endgroup\$
    – manatwork
    Mar 21, 2018 at 9:49
  • \$\begingroup\$ @manatwork I understood it as "catch and ignore any errors" but alright. \$\endgroup\$ Mar 21, 2018 at 10:35
1
\$\begingroup\$

Julia 0.6, 76 bytes

f(s)=match(Regex("$s(.[a-z]*)"),"RedOrangeYellowGreenBlueIndigoViolet"^2)[1]

Try it online!

This handles the Violet->Red by recycling the string with the power ^ operator.

Here's a slightly longer solution without regexes:

g(s,l=split("Red Orange Yellow Green Blue Indigo Violet"," "))=l[(findin(l,[s])[1])%7+1]
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 74 bytes

(-split("Red Orange Yellow Green Blue Indigo Violet "*2-split$args)[1])[0]

Try it online!

Takes the string "Red ... Violet " and string-multiplies it out by two to properly handle the Violet -> Red test case. We then -split that string on input $args to give us an array of two strings. We take the second string thereof [1], then -split that on whitespace to give us an array of strings and take the first [0].

For example, for input "Yellow", the first step will result in @("Red Orange ", " Green Blue Indigo ... Indigo Violet "). We take the second one of that, split it on whitespace (which removes the whitespace), resulting in @("Green", "Blue", ... "Violet"), so taking the [0] one thereof results in the proper next string.

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

IBM/Lotus Notes Formula Language, 79 74 bytes

@Left(@Right("Red Orange Yellow Green Blue Indigo Violet Red ";a+" ");" ")

Previous version for 79:

R:=@Explode("Red,Orange,Yellow,Green,Blue,Indigo,Violet,Red");R[@Member(a;R)+1]

Takes input from an editable text field called a.

There is no TIO for formula language so here's a couple of screenshots.

enter image description here

enter image description here

enter image description here

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

PHP, 92 bytes

$a=" Red   OrangeYellowGreen Blue  IndigoVioletRed";echo substr($a,strpos($a,$argv[1])+6,6)

Try it online!

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

Kotlin, 73 bytes

x->"RedOrangeYellow Green  BlueIndigoVioletRed".substringAfter(x).take(6)

Try it online!

Taking advantage of the fact that many colors are 6 characters, the ones that are not are prefixed with spaces to make them 6 characters long. Hopefully it's acceptable that some of the colors are outputted with spaces before them.
e.g. Red is " Red", Blue is " Blue"

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

SmileBASIC, 94 84 bytes

C$="Red   OrangeYellowGreen Blue  IndigoViolet
INPUT I$?MID$(C$*2,INSTR(C$,I$)+6,6)
\$\endgroup\$
1
\$\begingroup\$

Gema, 67 characters

*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}

Sample run:

bash-4.4$ echo -n Yellow | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Green

bash-4.4$ echo -n Violet | gema '*=@subst{*\?<J>=\?\$2\;\?=;RedOrangeYellowGreenBlueIndigoVioletRed}'
Red

Gema, 59 characters

R=Orange
O=Yellow
Y=Green
G=Blue
B=Indigo
I=Violet
V=Red
*=

Boring one. Dumbest approach ever, but quite short.

Sample run:

bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Yellow'
Green

bash-4.4$ gema 'R=Orange;O=Yellow;Y=Green;G=Blue;B=Indigo;I=Violet;V=Red;*=' <<< 'Violet'
Red
\$\endgroup\$
1
\$\begingroup\$

q/kdb+, 59 55 bytes

Solution:

.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]

Examples:

q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Red"
"Violet"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Orange"
"Red"
q).[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange]"Blue"
"Green"

Explanation:

Create a dictionary of colour => next colour, the input is the key to the dictionary:

.[!;2 8#($)`Red`Violet`Indigo`Blue`Green`Yellow`Orange] / the solution
.[ ;                                                  ] / apply multiple args to function
           `Red`Violet`Indigo`Blue`Green`Yellow`Orange  / list of colours
         ($)                                            / convert to strings
    2 8#                                                / reshape into 2x8 grid
  !                                                     / create dictionary

Bonus:

It's 53 bytes in K4:

.[!;2 8#$`Red`Violet`Indigo`Blue`Green`Yellow`Orange]
\$\endgroup\$
1
\$\begingroup\$

Japt, 45 43 bytes

-2 bytes thanks to Shaggy

`R‚sOÎÁƒYÁMwsGÎ9sBluƒI˜igosVio¤t`qs
g1+UbNg

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 43 bytes \$\endgroup\$
    – Shaggy
    Mar 22, 2018 at 0:22
  • \$\begingroup\$ @Shaggy Thanks! I forgot about N \$\endgroup\$
    – Oliver
    Mar 22, 2018 at 0:26
1
\$\begingroup\$

sed, 72 bytes

s/$/%RedOrangeYellowGreenBlueIndigoVioletRed/;s/(.+)%.*\1(.[a-z]+).*/\2/

Try it Online

Example 1:

Input:

Red
Orange
Yellow
Green
Blue
Indigo
Violet

Output:

Orange
Yellow
Green
Blue
Indigo
Violet
Red

Example 2:

Input:

Indigo
Yellow
Red
Red
Blue
Green
Orange
Violet
Green
Green
Green
Blue
Blue
Violet

Output:

Violet
Green
Orange
Orange
Indigo
Blue
Yellow
Red
Blue
Blue
Blue
Indigo
Indigo
Red
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to the site! Could you provide a link to an online interpreter, such as Try It Online! where we can test this solution? \$\endgroup\$ Mar 22, 2018 at 16:21
  • \$\begingroup\$ @cairdcoinheringaahing: Hi, thank you very much for the welcome and the website recommendation! I've updated my answer with a link to the page where you can test the code online. \$\endgroup\$
    – lucasb
    Mar 22, 2018 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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