73
\$\begingroup\$

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

enter image description here

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>

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Why hasn't anyone tried <>^Fish? \$\endgroup\$ Commented Nov 14, 2015 at 16:34
  • \$\begingroup\$ shortest amount of bytes total or in a given language? \$\endgroup\$ Commented Jan 6, 2023 at 22:31

104 Answers 104

4
\$\begingroup\$

Bash, 40 bytes

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

Not using any coreutils.

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

Batch, 147 127 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.

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

Labyrinth, 48 46 45 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).

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

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

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.

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

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.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ It's customary to count each additional file as one byte. That should apply to hard links too. \$\endgroup\$
    – Dennis
    Commented Nov 14, 2015 at 1:37
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 14, 2015 at 1:38
  • \$\begingroup\$ @Dennis you beat me to it by 35 seconds. Business as usual ;-) \$\endgroup\$ Commented Nov 14, 2015 at 1:39
3
\$\begingroup\$

Vitsy, 23 22 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.
\$\endgroup\$
3
\$\begingroup\$

Python 2 - 75 bytes

import sys
l,n=sys.stdin.read()
print 'light'if ord(l)&1^int(n)&1 else'dark'
\$\endgroup\$
3
\$\begingroup\$

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)
}
\$\endgroup\$
3
  • \$\begingroup\$ You can save a byte using !k%2 (unless I'm mistaken about precedence) \$\endgroup\$
    – cat
    Commented May 18, 2016 at 1:04
  • 1
    \$\begingroup\$ @cat Go does not support boolean operators on ints \$\endgroup\$ Commented May 18, 2016 at 12:49
  • \$\begingroup\$ Uhh... oh. I forgot about that. Go gets a little lamer every time I come back to it. \$\endgroup\$
    – cat
    Commented May 18, 2016 at 13:00
3
\$\begingroup\$

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"))
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ main=interact$(cycle["dark","light"]!!).sum.map fromEnum for 56 bytes. \$\endgroup\$
    – lynn
    Commented Nov 15, 2015 at 15:38
3
\$\begingroup\$

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.

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

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.
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ Requires input from STDIN, not a function. \$\endgroup\$ Commented Nov 16, 2015 at 0:59
  • \$\begingroup\$ I didn't see that part. Edited \$\endgroup\$
    – Cyoce
    Commented Nov 16, 2015 at 6:21
  • \$\begingroup\$ You can save a couple of bytes by using ^ instead of - - and the 0 is unnecessary. \$\endgroup\$
    – Neil
    Commented Nov 18, 2015 at 0:31
3
\$\begingroup\$

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]}
\$\endgroup\$
2
  • \$\begingroup\$ Looks like your code reverses the colors. 1 character shorter: x=(light dark);echo ${x[19#`cat`%2]} \$\endgroup\$
    – manatwork
    Commented Nov 14, 2015 at 15:16
  • \$\begingroup\$ @manatwork Thanks. When I tried the array indexing trick before it turned out longer - not sure what I got wrong. Thanks! \$\endgroup\$ Commented Nov 14, 2015 at 21:01
3
\$\begingroup\$

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   
\$\endgroup\$
5
  • \$\begingroup\$ Was MATL written before this challenge? \$\endgroup\$
    – lirtosiast
    Commented Dec 18, 2015 at 21:33
  • \$\begingroup\$ 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. \$\endgroup\$
    – flawr
    Commented Dec 18, 2015 at 21:43
  • \$\begingroup\$ 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. \$\endgroup\$
    – rayryeng
    Commented Dec 18, 2015 at 22:17
  • \$\begingroup\$ Vert nice use of mod! \$\endgroup\$
    – Luis Mendo
    Commented Dec 18, 2015 at 23:08
  • \$\begingroup\$ Well I basically just translated my matlab answer=) \$\endgroup\$
    – flawr
    Commented Dec 18, 2015 at 23:48
3
\$\begingroup\$

PowerShell, 52 46 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.

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

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!

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

Julia 1.0, 43 bytes

print([:dark,:light][sum(read(stdin))%2+1])

Try it online!

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

Shue, 80 bytes

light
dark
bb=
b=light
=dark
a=
c=
d=b
e=
f=b
g=
h=b
1=
2=b
3=
4=b
5=
6=b
7=
8=b

Try it online!

Pretty sure this is optimal. The empty string represents even letters/integers and a "b" represents odd letters/integers.

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

Factor + math.unicode, 36 35 bytes

readln Σ odd? "light""dark"? print

Try it online!

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

Fig, \$11\log_{256}(96)\approx\$ 9.054 bytes

iHD,[jn("OS

Try it online!

iHD,[jn("OS
          S # Sum charcodes
         O  # Is odd?
i           # Use that as the index for...
  D,[jn("   # The compressed string "darklight"
 H          # Halved, yielding ["dark", "light"]
\$\endgroup\$
3
\$\begingroup\$

K (ngn/k), 25 bytes

{$[2!+/x;"light";"dark"]}

Try it online!

Simple if statement.

Explanation:

{$[2!+/x;"light";"dark"]}    Main function. Takes x as input
 $[                    ]     If
     +/x                     Sum of ASCII charcodes of x
    !                        Modulo by
   2                         2
        ;                    If the result is 1 (i.e. an odd number)
         "light"             Return string "light"
                ;"dark"      Else, return string "dark"
\$\endgroup\$
1
  • \$\begingroup\$ hint: use indexing, symbols, and a train shorten it by ≈⅓ \$\endgroup\$
    – ngn
    Commented Oct 12, 2022 at 13:12
2
\$\begingroup\$

Microscript, 25 bytes

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

2sI++%{"thgil"ah}"krad"ah
\$\endgroup\$
2
\$\begingroup\$

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.
#         Discard the accumulator.
!         Evaluate the modified input. Pushes two integers.
+         Add the 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.
#         Discard the topmost string.
\$\endgroup\$
2
\$\begingroup\$

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

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.

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

><>, 31 bytes

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

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

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

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])
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 54 bytes \$\endgroup\$
    – Giuseppe
    Commented Oct 5, 2017 at 20:58
2
\$\begingroup\$

Scala, 65 53 49 bytes

It's quite clear without ungolfing.

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

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.