# 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? Nov 14 '15 at 16:34

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

# Labyrinth, 484645 42 bytes

Thanks to Sp3000 for saving two bytes.

-,"
#
%0:::8.5.3.4.116.@
1
00.97.114.107.@


Try it online!

### Explanation

The beginning of the code is a funny dead end. Remember that Labyrinth assumes an infinite number of zeroes when it requires operands at the bottom of the stack. The code starts one the - going right, which tries to subtract two numbers, so the stack becomes:

[ ... 0 ]


Then , reads the first character, a say:

[ ... 0 97 ]


The " is a no-op, but this is also a dead-end so the instruction pointer turns around and starts going to the left. Then  reads the other character, 2 say:

[ ... 0 97 50 ]


This time, - subtracts those two numbers:

[ ... 0 47 ]


The IP now follows the bend of the "corridor". The # gets the stack depth, ignoring the implicit zeroes, which conveniently happens to be 2:

[ ... 0 47 2 ]


And % computes the modulo:

[ ... 0 1 ]


At this point, the IP is at a junction. If the top of the stack is zero, it will move straight ahead, where 100.97.114.107.@ prints dark. But if the top of the stack is non-zero (specifically, 1), it will move to the right, where 0:::8.5.3.4.116.@ prints light (note that we can omit the leading 1, because there is already a 1 on the stack, and we can save on the repeated 10 in 108, 105, 103, 104 by making a few copies of the 10 when we first get there).

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


## ><>, 31 bytes

ii+2%?\"krad"oooo;
l"oc0.\"thgi


Here I'm thinking "there's got to be a better way..."

# Perl, 29 27 bytes

$_=/./&($'+ord)?light:dark


This code requires the -p switch, which I have counted as 1 byte.

Try it online on Ideone.

### How it works

• Because of the -p switch, Perl reads one line of input and stores it in $_. • /./ is a regular expression that matches one character. This has two implications: • Since the match is successful, /./ returns 1. • The post-match (second input character) is stored in $'.

• $'+ord adds the integer the second input character represents to the code point (ord) of the first character of the implicit variable $_.

• & takes the bitwise AND of the return value of /./ and the sum $'+ord, returning 1 is the sum if odd, 0 if it is even. • ?light:dark returns light if the previous expression returned 1 and dark otherwise. • Finally $_= assigns the result to _, which Perl prints automatically, because of the -p switch. ## 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. 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. Nov 14 '15 at 1:38 • @Dennis you beat me to it by 35 seconds. Business as usual ;-) 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 "krad" "thgil" How it works: z+2M1+mZ z Grab all input as string. + Add it together. 2M Modulo by 2. 1+ Add 1 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 l,n=sys.stdin.read() 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 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 ## 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"))  # Haskell, 61 56 Bytes -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. Nov 16 '15 at 0:59
• I didn't see that part. Edited 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]} 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! 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? 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. 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. Dec 18 '15 at 22:17
• Vert nice use of mod! Dec 18 '15 at 23:08
• Well I basically just translated my matlab answer=) Dec 18 '15 at 23:48

("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* Nov 17 '15 at 19:28 • @Rynant Or, use + and drop the parens to save 6. ;-) Nov 17 '15 at 19:36 • Even better; nice! Nov 17 '15 at 19:48 C# (Visual C# Interactive Compiler) - 122 42 Write((Read()+Read())%2<1?"dark":"light");  • Reads from STDIN • Format is simply a1 Thanks to @dana for the change from C# to the current one & golfing a ton of bytes! :) Try It Online! # 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'
"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])

• 54 bytes Oct 5 '17 at 20:58

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:
Read 1 item
light

1: d4
2:
Read 1 item
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! 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]]) Nov 16 '15 at 1:50

# 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; Nov 16 '15 at 15:20
• @Martijn Sometimes you can't see the simplest things. Thanks a lot. Nov 16 '15 at 15:42

## 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 Jun 1 '18 at 10:34