# Determine the color of a chess square

Your challenge is to write a program that outputs the color of a given square from the chessboard. This is how a chessboard looks:

You can see that the square a1 is dark, and h1 is a light square. Your program needs to output dark or light, when given a square. Some examples:

STDIN:  b1
STDOUT: light

STDIN:  g6
STDOUT: light

STDIN:  d4
STDOUT: dark


The rules:

• You need to provide a full program that uses STDIN and uses STDOUT to output dark or light.
• Assume that the input is always valid ([a-h][1-8])
• This is , so shortest amount of bytes wins!

# Scoreboard

var QUESTION_ID=63772,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• Why hasn't anyone tried <>^Fish? – ghosts_in_the_code Nov 14 '15 at 16:34

## Brian & Chuck, 66 bytes

,>,_{->-?+{-_?>}<?light{-_?>}>>?dark?
II{<?}<<<?{<{<<<?_>.>.>.>.>.


Probably still golfable, but I think I'd need another approach.

### Explanation

,>, reads input into Chuck, replacing the two Is. Next is the following part of the code:

   _{->-?
{<?


which decrements both input elements until the latter (i.e. the digit) reaches zero. This stops Brian's ? from passing control to Chuck, continuing on.

The next + increments the zeroed digit to a 1 so that following uses of { don't get caught on it. At this point, the first cell of Chuck's tape has the difference of the two code points, so now we need to take the code point modulo 2. This is done with the following parts:

          A            B            C
{-_?>}<?     {-_?>}>>?    ?
}<<<?{<{<<<?


I've labelled the three parts on Brian's tape to make things easier to explain. The {- in parts A and B decrement the first cell on Chuck's tape, and the following ? checks if it's zero. If it's not, then control is passed, and we execute }<<<?. For part A, this moves us to part B. For part B, this moves us to part C, which immediately passes control and we execute {<{<<<?, sending us back to part A. Thus the effect is that we alternate between parts A and B, in a state machine-like way.

Now whether the first cell was zeroed while we were in part A or part B determines what we print. For A, we have:

             ?>}<?light
_               ?_>.>.>.>.>.


which executes >}< to position us on the last ? in Chuck's tape, and then runs >. five times to print "light".

On the other hand, for part B, we have:

                          ?>}>>?dark?
_                _>.>.>.>.>.


which executes >}>> to position us on the first . in Chuck's tape, and then runs >. four times to print "dark".

## Brainfuck, 132 bytes

>,>,[<->-]<[->+<[->-]<[<]>]<++++++++++[->++++++++++<]>>[<++++++++.---.--.+.++++++++++++.>->+<]>-[<<.---.+++++++++++++++++.-------.<]


I tried coming up with my own mod 2 algorithm, which is the [->+<[->-]<[<]>].

# Batch, 248223 207 bytes

Because Batch lacks disjunctional conditionals. -18 bytes thanks to @dohaqatar7, and more due to his idea.

@ECHO OFF
SET S=SET
%S%/P I=
%S%L=%I:~0,1%
%S%I=IF %L%==
%S%N=%I:~-1%
%S%A= %S%L=
%I%a%A%0
%I%b%A%1
%I%c%A%0
%I%d%A%1
%I%e%A%0
%I%f%A%1
%I%g%A%0
%I%h%A%1
%S%/A R=N%%2
IF %R%%L% (ECHO light) ELSE (ECHO dark)

• I'm not on a windows machine so I can't test right now but, you should be able to save some bytes by abusing variable expansion. Put set a=" set L=" at the top then replace every occurrence of  set L= with %a%. – ankh-morpork Nov 16 '15 at 23:09
• @dohaqatar7 Oh right you can do that. Thanks! – Conor O'Brien Nov 16 '15 at 23:18

## Bash, 40 bytes

read x;y=(light dark);echo ${y[19#$x%2]}


Not using any coreutils.

## Batch, 147127 126 bytes

@set/pi=
@set/aj=%i:~1%%%2
@goto %i:~,1%
:a
:c
:e
:g
@set/aj=1-j
:b
:d
:f
:h
@if %j%==0 (echo dark)else echo light


Uses goto as a form of switch to increment the row number on alternate columns.

Edit: Saved 15 bytes by reducing the column modulo two up front and then using 1-j to flip between dark and light on alternate columns. Saved 2 bytes by removing some unnecessary ()s. Saved 3 4 bytes by removing some unnecessary spaces.

## Gol><>, 22 bytes

ii+2%Q"thgil"H|"krad"H


### Explanation

ii             Read two chars
+2%            Add code points mod 2
Q        |     If top of stack is truthy...
"thgil"H        Push "light" and halt, outputting stack
"krad"H        Push "dark" and halt, outputting stack


## CMD.EXE, 15 + 15 + 10 + 63 = 103 bytes

a1.cmd:

echo dark
exit


a2.cmd:

echo light
exit


Then create hard links for all the remaining 62 squares. Invoke using cmd /k echo off.

• It's customary to count each additional file as one byte. That should apply to hard links too. – Dennis Nov 14 '15 at 1:37
• I think the consensus is that each additional file after the 1st costs you an extra point. I would argue that hard links count as files for this purpose. – Digital Trauma Nov 14 '15 at 1:38
• @Dennis you beat me to it by 35 seconds. Business as usual ;-) – Digital Trauma Nov 14 '15 at 1:39

# Vitsy, 2322 21 Bytes

Thanks to @El'endiaStarman for shaving off a byte!

New Method (using fancy stack mechanics):

"krad"&"thgil"z+2M(?Z

Explanation:

"krad"&"thgil"z+2M(?Z
"krad"                 Push "dark" (backwards) to the stack.
&                Generate a new stack.
"thgil"         Push "light" (backwards) to the stack.
z        Grab all input as string.
+       Add up the input's ASCII values.
2M     Modulate by 2.
(    If the result is not zero, do the next item.
?   Rotate over a stack.
Z  Output everything in the current stack.

Original Method (using fancy line-specific execution mechanics):

z+2M1+mZ
"thgil"

How it works:

z+2M1+mZ
z        Grab all input as string.
2M     Modulo by 2.
m  Go to the line specified by the top item of the stack - if it's one,
it'll push "light" to the stack. If 2, "dark".
Z Output everything in the stack.

# Python 2 - 75 bytes

import sys
print 'light'if ord(l)&1^int(n)&1 else'dark'


# Go, 100 bytes

package main;import."os";func main(){t:=Args[1];k,d:=t[0]+t[1],"light";if k%2==0{d="dark"};print(d)}


Ungolfed:

package main

import . "os" // Import os defines into current namespace

func main() {
t := Args[1] // Grab the first argument
// Define k as the sum of the 2
// first characters of the first argument, then define d as "light"
k, d := t[0]+t[1], "light"
// The sum aligns up nicely with the color of the square
if k%2 == 0 {
d = "dark"
}
print(d)
}

• You can save a byte using !k%2 (unless I'm mistaken about precedence) – cat May 18 '16 at 1:04
• @cat Go does not support boolean operators on ints – Kristoffer Sall-Storgaard May 18 '16 at 12:49
• Uhh... oh. I forgot about that. Go gets a little lamer every time I come back to it. – cat May 18 '16 at 13:00

# PHP, 40 42 bytes

PHP is doing OK this time:

<?=intval(fgets(STDIN),35)%2?dark:light;


Edits

• Saved 2 bytes by using <?= instead of echo. Thanks to Martijn.
• 40 chars: <?=intval(fgets(STDIN),35)%2?dark:light; – Martijn Nov 16 '15 at 15:20
• @Martijn Sometimes you can't see the simplest things. Thanks a lot. – insertusernamehere Nov 16 '15 at 15:42

## Common Lisp, 90 bytes

Not a winner, but makes nice use of ability to read in base 18 and then do arithmetic with that number.

(let((*read-base* 18))(if(evenp(multiple-value-call'logxor(floor(read)18)))"light""dark"))


-5 bytes thanks to Mauris

As always, Haskell's interact function comes through with some byte saving on a challenge with IO.

The program assumes that a STDIN consists of only the row and the column, anything else can throw off the results; although, a trailing newline will not effect the outcome.

main=interact$(cycle["dark","light"]!!).sum.map fromEnum  • main=interact$(cycle["dark","light"]!!).sum.map fromEnum for 56 bytes. – Lynn Nov 15 '15 at 15:38

## Marbelous, 86 bytes

..00
..]]//
&0/\]]//
..&0//
..//
^0
=0&1
&2\/
\/
'l'i'g'h't'd'a'r'k
&1&1&1&1&1&2&2&2&2


]]// loops wait for two bytes of input, then add them together and use ^0 and =0 to check the LSB and drop "light" or "dark" to stdout.

# Bash, 69 Bytes

sed 's/^./(&+/;s/$/)%2/'|tr [a-h] [1-8]|bc|sed s/1/light/\;s/0/dark/  Probably could be optimized a bit more. • The first sed formats the input to be from the form a5 to (a+5)%2 • tr takes the letters a-h and converts them to 1-8 respectively • bc performs the addition and modulo • the final sed then takes the result and formats it as a string. ## JavaScript ES6, 59 56 s=prompt() alert((s.charCodeAt()^s[1])%2?"light":"dark")  Extracts the number and the ASCII code of the letter, adds them and checks if even/odd. This can accept input in the form a1 and A1 3 bytes saved thanks to Neil! • Requires input from STDIN, not a function. – Conor O'Brien Nov 16 '15 at 0:59 • I didn't see that part. Edited – Cyoce Nov 16 '15 at 6:21 • You can save a couple of bytes by using ^ instead of - - and the 0 is unnecessary. – Neil Nov 18 '15 at 0:31 # Bash + coreutils, 34 36 Using the same base conversion technique as other answers, but I chose base 19. I think it should work for any odd base between 19 and 35. x=(light dark) echo${x[19#cat%2]}

• Looks like your code reverses the colors. 1 character shorter: x=(light dark);echo ${x[19#cat%2]} – manatwork Nov 14 '15 at 15:16 • @manatwork Thanks. When I tried the array indexing trick before it turned out longer - not sure what I got wrong. Thanks! – Digital Trauma Nov 14 '15 at 21:01 # MATL, 20 bytes js2\?'light'}'dark']  Explanation j % input string s % sum 2 % push 2 \ % mod(sum(inputstring),2) ? % if this value is 1 'light' % return 'light' } % else 'dark' % return 'dark' ] % end  • Was MATL written before this challenge? – lirtosiast Dec 18 '15 at 21:33 • Oh, I forgot about that. The first version was published in october as far as I know, but I am not sure whether this is valid code in the first version. – flawr Dec 18 '15 at 21:43 • Yes, the language was in draft in October with a preliminary version of the interpreter also available. The esolangs.org page was also created at that time... so I think you're good here flawr. – rayryeng - Reinstate Monica Dec 18 '15 at 22:17 • Vert nice use of mod! – Luis Mendo Dec 18 '15 at 23:08 • Well I basically just translated my matlab answer=) – flawr Dec 18 '15 at 23:48 # PowerShell, 5246 45 bytes ("dark","light")[(+($a="$input")[0]+$a[1])%2]


Pretty ugly due to how we have to parse the STDIN input (which, in PowerShell, is weird). The special variable $input is present only if items get piped in, we encapsulate that into a string, and save it into $a. Then, we use the same math trick as other answers to calculate out whether the input is even or odd, and use that to index into our "dark" or "light" output array.

Edit -- saved 6 bytes by using + to cast $a[0] instead of [int]. Saved an additional byte by changing where $a is created by using a code block.

• You can drop 3 bytes by replacing [int] with 1* – Rynant Nov 17 '15 at 19:28
• @Rynant Or, use + and drop the parens to save 6. ;-) – AdmBorkBork Nov 17 '15 at 19:36
• Even better; nice! – Rynant Nov 17 '15 at 19:48

# Microscript, 25 bytes

Because Microscript II really doesn't have much in terms of character manipulation yet.

2sI++%{"thgil"ah}"krad"ah


# ShapeScript, 57 56 bytes

0'1+@"%c"2?862**+%$"%d"2?%~@'8*!#!+"dark"@"light"@'@'*!#  Try it online! ### How it works 0 Push 0 (accumulator). ' Push a string that, when evaluated, does the following: 1+ Increment the accumulator. @ Swap it with the input. "%c" Push that formatting string. 2? Copy the accumulator. 862**+ Add 8 * 6 * 2 = 96 to it. % Apply the string formatting: 1 ... 8 -> 'a' ... 'h'$         Split the input at occurrences of that character.
"%d"      Push that formatting string.
2?        Copy the accumulator.
%         Apply the string formatting: 1 ... 8 -> '1' ... '8'
~         Join the split input, using that character as separator.
@         Swap the result with the accumulator.
'
8*        Repeat the string eight times.
!         Evaluate.
!         Evaluate the modified input. Pushes two integers.
"dark"@   Swap the sum with that string.
"light"@  Ditto.
'@'*!     Repeat the at sign (swap) that many times and evaluate the result.
An odd number of swaps brings "dark" on the top of the stack.


# Mouse, 25 bytes

?'?'+2\["light"$]"dark"$


Explanation:

?'?'                       ~ Read two characters from STDIN and put their ASCII
~ codes on the stack
+2\                    ~ Get the sum of the codes modulo 2
["light"$] ~ If the result is 1, print light to STDOUT and exit "dark"$   ~ Print dark to STDOUT and exit


# SpecBAS - 59 bytes

My original version (before looking at any other answers) was 117 bytes and probably reflects the way I come at a problem. Then I saw everyone using base 19 or 35, which wouldn't have sprung to my mind at all.

So, with thanks to everyone else for getting this down to 59.

1 INPUT s$: PRINT IIF$(DECIMAL(s\$,19) MOD 2,"Dark","Light")


Prints "Dark" if converted number mod 2 is 1/True and "Light" otherwise, using the inline if statement.

# R, 65 bytes

cat(c("dark","light")[1+sum(strtoi(charToRaw(scan(,"")),16))%%2])


Ungolfed:

# Get the ASCII codes from the input string
a <- strtoi(charToRaw(scan(, "")), 16L)

# Compute the sum modulo 2
s <- sum(a) %% 2

# Use the sum as an index for the output
cat(c("dark", "light")[s + 1])


Scala, 65 53 49 bytes

It's quite clear without ungolfing.

print(Seq("dark","light")(readLine.sum.toInt%2))


# GolfScript, 21 bytes

{^}*~1&"lightdark"5/=


Explanation:

{^}*            # XOR the bytes of the input together
~               # negate the result
1&              # extract only the lowest bit (i.e. 0 or 1)
"lightdark"5/   # split the string "lightdark" into the array ["light" "dark"]
=               # use the bit as an index into the array, returning "light"
# for 0 and "dark" for 1


Conveniently, since the ASCII codes of a Unix-style newline (LF = ASCII 10) and a space (ASCII 32) are even, this code can handle arbitrary spaces and linefeeds in its input. Both upper- and lowercase letters are also accepted, and the letter can be given before or after the number. Tabs or carriage returns, however, will throw it off.

Not unexpectedly, this program is quite similar to Peter Taylor's CJam entry. I didn't actually look at any of the other entries before I wrote this, though.

# R, 163 bytes

Thanks to Alex A. for helping me with this answer.

n<-toupper(unlist(strsplit(scan(,""),"")));cat(matrix(rep(c(rep(c("light","dark"),4),rep(c("dark","light"),4)),4),8,8,dimname=(list(8:1,LETTERS[1:8])))[n[2],n[1]])


### Example usage

1: b1
2:
light

1: d4
2:
dark


There's surely a better way to do this. I just made a matrix filled with the string "light" or "dark" to match the chessboard and then used subscripts taken from the input to return the color of the square.

• Alright, I took your suggestions and fixed it. Thanks for your help! – syntonicC Nov 16 '15 at 0:52
• Here's some tips for golfing in R. Couple of things that stand out. Replace <- with =. toupper isn't required, but you'll need to use letters rather than LETTERS. You could create a 9 x 9 matrix using matrix(c('dark','light'),9,9). It will throw a warning, but I don't think that's a problem. You could also play around with charToRaw. So keeping the same sort of logic you could reduce it to something like cat(matrix(c('dark','light'),9,9)[(n=as.integer(charToRaw(scan(,'')))-c(96,48))[1],n[2]]) – MickyT Nov 16 '15 at 1:50

## Burlesque, 25 bytes

)**++"dark light"wdcyj!!Q


One-to-one translation from the 56 bytes Haskell solution to this challenge:

)**++             -- sum . map fromEnum
"dark light"wdcy  -- cycle["dark","light"]
j                 -- swap
!!                -- same as Haskell !!


# Prolog, 80 bytes

p:-read(X),string_codes(X,[A,B]),Y is(A+B)mod 2,(Y=0->write(dark);write(light)).


Try it online here

• /\1 instead of mod 2 + removing the parens around (A+B) saves a few bytes – ASCII-only Jun 1 '18 at 10:34

# PlatyPar, 21 bytes

This is a non-competing answer, as I made this language after the posting of this question. It was neither made for this question nor has it been augmented to fit this specific question.

X,u#^2%?"dark"\"light


Explanation

X,u#^                  ## charcode of the letter XOR the number
2%?      \        ## if it is odd
"dark"         ## output "dark"
"light  ## else output "light