# 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

• "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? – recursive Mar 21 '18 at 6:52
• Are lower case colours okay? – Emigna Mar 21 '18 at 8:32
• But what happens when you reach 'gray'? ;) – AJFaraday Mar 21 '18 at 11:24
• @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. – sonrad10 Mar 21 '18 at 13:47
• Are trailing spaces okay? – ivzem Mar 22 '18 at 17:45

# 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


# 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;
}

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

# 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!

# 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!

# 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! • Almighty Unicode names – Weijun Zhou Mar 21 '18 at 14:54 • 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? – Dennis Mar 21 '18 at 15:01 • There is also a %12 solution for Coconut, but of course this is neater. – Weijun Zhou Mar 21 '18 at 18:44 # 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.

• very nice, -2 bytes (/#$_/ interpolates) – Asone Tuhid Mar 21 '18 at 12:56 # Red, 87 bytes func[c][print first find/tail[Red Orange Yellow Green Blue Indigo Violet Red]to-word c]  Try it online! • 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. – msh210 Mar 21 '18 at 12:50 • @ 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). – Galen Ivanov Mar 21 '18 at 13:10 # 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  # 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")  # 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)


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.

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

## 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.

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

# Vim, 595653 52 Bytes

-1 byte thanks to tsh

2IYellow Green Blue Indigo Violet Red Orange <Esc>*wywVp
• 2IYellow Green Blue Indigo Violet Red Orange <Esc>*wywVp – tsh Mar 21 '18 at 12:14

# Java (JDK 10), 77 bytes

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


Try it online!

## Credits

• – Kevin Cruijssen Mar 21 '18 at 10:39
• @KevinCruijssen That some nice regex fu that you've got! – Olivier Grégoire Mar 21 '18 at 11:00
• I remembered when I once was looking for a split which keeps delimiters as separated items that the answer I found also contained options to keep the delimiter concatted as either leading or trailing part, and figured it would be useful here. :) Here is that answer including the look-ahead / look-behind for the other two options mentioned. – Kevin Cruijssen Mar 21 '18 at 11:48
• Save a byte: s->"Red Orange Yellow Green Blue Indigo Violet Red".split(s)[1].split(" ")[1] – Okx Mar 21 '18 at 20:44

# Coconut, 79 bytes

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


Try it online!

• 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] – Wernisch Mar 21 '18 at 12:46
• @Wernisch Thanks for the suggestion. Though I'll wait until OP has responded whether lowercase letters are acceptable before updating. – Laikoni Mar 21 '18 at 13:09

# 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)


# Stax, 3130 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

• ok... I love these languages =) – lolad Mar 21 '18 at 8:16
• Fails for Violet -> Red – Weijun Zhou Mar 21 '18 at 12:19
• @WeijunZhou: That test case was added after this submission. – recursive Mar 21 '18 at 14:26
• @WeijunZhou: I fixed that test case and shaved a byte. – recursive Mar 22 '18 at 4:05
• @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. – recursive Mar 22 '18 at 5:58

# J, 67 64 62 bytes

-2 bytes thank to FrownyFrog

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


Try it online!

• &. actually works for this. Try it online – FrownyFrog Mar 21 '18 at 21:40

# 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

• 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 :) – Giuseppe Mar 22 '18 at 18:33
• oops, looks like colors() doesn't contain indigo! Ah well, still, +1! – Giuseppe Mar 22 '18 at 18:38
• thanks! match is better here – DS_UNI Mar 23 '18 at 14:02
• 91 bytes – Giuseppe Mar 23 '18 at 14:04
• and yeah I first tried to use colors() :/ – DS_UNI Mar 23 '18 at 14:04

## 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.

a=%w{Red Orange Yellow Green Blue Indigo Violet};p a[-~(a.index$_)%7]  Try it online! • Why the i&& thing? No need to check for nil, as “Ignore any errors if this is not a colour.” – manatwork Mar 21 '18 at 9:49 • @manatwork I understood it as "catch and ignore any errors" but alright. – Asone Tuhid Mar 21 '18 at 10:35 # 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]


# 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.

# 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.

# PHP, 92 bytes

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


Try it online!

# 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"

# SmileBASIC, 94 84 bytes

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


# 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


# q/kdb+, 59 55 bytes

Solution:

.[!;2 8#($)RedVioletIndigoBlueGreenYellowOrange]  Examples: q).[!;2 8#($)RedVioletIndigoBlueGreenYellowOrange]"Red"
"Violet"
q).[!;2 8#($)RedVioletIndigoBlueGreenYellowOrange]"Orange" "Red" q).[!;2 8#($)RedVioletIndigoBlueGreenYellowOrange]"Blue"
"Green"


Explanation:

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

.[!;2 8#($)RedVioletIndigoBlueGreenYellowOrange] / the solution .[ ; ] / apply multiple args to function RedVioletIndigoBlueGreenYellowOrange / list of colours ($)                                            / convert to strings
2 8#                                                / reshape into 2x8 grid
!                                                     / create dictionary


Bonus:

It's 53 bytes in K4:

.[!;2 8#$RedVioletIndigoBlueGreenYellowOrange]  # Japt, 45 43 bytes -2 bytes thanks to Shaggy R‚sOÎÁƒYÁMwsGÎ9sBluƒI˜igosVio¤tqs g1+UbNg  Try it online! • 43 bytes – Shaggy Mar 22 '18 at 0:22 • @Shaggy Thanks! I forgot about N – Oliver Mar 22 '18 at 0:26 # 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
`
• Welcome to the site! Could you provide a link to an online interpreter, such as Try It Online! where we can test this solution? – caird coinheringaahing Mar 22 '18 at 16:21
• @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. – lucasb Mar 22 '18 at 19:07