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

2
\$\begingroup\$

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.

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ Alright, I took your suggestions and fixed it. Thanks for your help! \$\endgroup\$
    – syntonicC
    Commented Nov 16, 2015 at 0:52
  • 3
    \$\begingroup\$ 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]]) \$\endgroup\$
    – MickyT
    Commented Nov 16, 2015 at 1:50
2
\$\begingroup\$

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.
\$\endgroup\$
2
  • 2
    \$\begingroup\$ 40 chars: <?=intval(fgets(STDIN),35)%2?dark:light; \$\endgroup\$
    – Martijn
    Commented Nov 16, 2015 at 15:20
  • 2
    \$\begingroup\$ @Martijn Sometimes you can't see the simplest things. Thanks a lot. \$\endgroup\$ Commented Nov 16, 2015 at 15:42
2
\$\begingroup\$

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

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

\$\endgroup\$
1
  • \$\begingroup\$ /\1 instead of mod 2 + removing the parens around (A+B) saves a few bytes \$\endgroup\$
    – ASCII-only
    Commented Jun 1, 2018 at 10:34
2
\$\begingroup\$

Lua, 53 Bytes

l,n=(...):byte(1,2)print(l%2==n%2 and"dark"or"light")

Pretty simple, takes command line input through ... and assigns variables l and n to the first and second byte of the input and then checks the ASCII value of each. If both are even or both are odd, the square is dark, else the square is light.

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

><> Fish 26 bytes

d"darkthgil"ii+2%?!rooooo;

A spin on the already posted fish code by sp3000.

It uses the same based checking with mod but with a few changes.

Using 1 line allows us to save 6 bytes (1 for the new line, 2 for directional instructions and 3 for the jump instructions)

Lose 1 byte to placing a [CR] onto the stack but it allows us to use 5 prints on both answers.

Lose 1 byte to reversing the stack [r] when needed for an answer.

Lastly putting both answers on the stack in 1 string allows us to save 2 bytes not having to use ["] twice.

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

SmileBASIC, 66 bytes

INPUT L$N=INSTR(@bdfh,L$)<0!=VAL(POP(L$))MOD 2?"light"*N;"dark"*!N

explanation:

INSTR(@bdfh,L$)<0 'Checks if L$ is b,d,f,h. @bdfh is a label, equivalent to the string "@bdfh"
!= 'used as a logical XOR, which SB doesn't have.
VAL(POP(L$))MOD 2 'Checks if the row is odd. Also removes the second character of L$, 
                   'which makes the first check shorter since SB evaluates right to left.
?"light"*N;"dark"*!N 'this turned out to be shorter than using IF/THEN/ELSE.
\$\endgroup\$
2
\$\begingroup\$

Jelly, 11 bytes

OḂEị“_ß“ṗɠ»

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why not just OSị“ṗɠ“_ß» for 10 bytes? \$\endgroup\$ Commented May 24, 2020 at 8:55
2
\$\begingroup\$

K (oK), 16 bytes

`dark`light 2!+/

Try it online!

+/ sum the (code points of the) argument

2! mod-2

`dark`light  select that from this list of symbols

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

PlatyPar, 21 bytes

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

Try it online!

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

Vyxal, 11 bytes

C∑₂`⟇ǎ↔β`½i

Try it Online!

Explanation:

C∑₂`⟇ǎ↔β`½i ; takes the coordinate
C           ; character values of the input
 ∑          ; sum of char values
  ₂         ; is even?
   `⟇ǎ↔β`   ; compressed string "lightdark"
         ½  ; split in half (yielding ["light", "dark"])
          i ; index into
\$\endgroup\$
2
\$\begingroup\$

Haskell + hgl, 31 bytes

main=io$(Wr"dark light"!)<mF Or

Attempt This Online!

Explanation

All in all we sum the code points and select the correct color based on its value mod 2.

  • Or converts a character to its codepoint
  • mF Or folds along a string to sum up the codepoints
  • Wr splits the string "dark light" along spaces.
  • ! indexes the string wrapping around if the index is greater than 1.
  • io converts a function into a complete program
  • main= sets the main and is required by Haskell for complete programs

Reflection

hgl is not good for complete programs. It has the 5 byte penalty forced by a main declaration, and requires some type glue, in this case io, to work. 8 bytes here are devoted to making this a complete program.

This challenge also has stringent io which contributes a lot to the size of the program.

With that in mind the actual logic here is 5-6 bytes which is alright.

Some reflections:

  • hgl has no string compression. Obviously, since it can't have dedicated syntax, it wouldn't be as effective as other golfing languages, and it would also be a large undertaking to implement it. But it potentially could have saved in this challenge.
  • There's an argument to be had that Wr should be 1 byte. If you want to make lists of strings, Wr"..." is usually the way to go.
  • (!) does not seem to have a prefix variant. It wouldn't help here, even if it were 1 byte, but it should probably exist with a 2-byte name.
\$\endgroup\$
2
\$\begingroup\$

Thunno B, \$17 \log_{256}(96) \approx\$ 14 bytes

S"ldiagrhkt"ZlsAH

Attempt This Online!

S"ldiagrhkt"ZlsAH   # Implicit input. The B flag gets the ordinals of each character in the input.
S                   # Sum the ordinals
 "ldiagrhkt"        # String "ldiagrhkt"
            Zl      # Uninterleaved to get ['light', 'dark']
              sAH   # Index into this list (1-based, modular)
                    # Implicit output
\$\endgroup\$
2
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 36 35 bytes

00000000: b408 cd21 8ad0 cd21 32c2 ba1e 01d0 e873  ...!...!2......s
00000010: 02b2 18b4 09cd 21c3 6c69 6768 7424 6461  ......!.light$da
00000020: 726b 24                                  rk$

Listing:

B4 08       MOV  AH, 8              ; DOS read char from STDIN 
CD 21       INT  21H                ; first char in AL 
8A D0       MOV  DL, AL             ; move to DL  
CD 21       INT  21H                ; second char in AL 
32 C2       XOR  AL, DL             ; XOR ASCII values to get low bit 
BA 011F     MOV  DX, OFFSET D       ; default to "dark" string 
D0 E8       SHR  AL, 1              ; put low bit into CF 
73 03       JNC  TO_STDOUT          ; if 1, output "dark" 
B2 18       MOV  DL, LOW OFFSET L   ; otherwise, "light" 
        TO_STDOUT: 
B4 09       MOV  AH, 9              ; DOS write string to STDOUT 
CD 21       INT  21H                ; DX written to STDOUT 
C3          RET                     ; return to DOS 
                 
        L   DB   'light$' 
        D   DB   'dark$' 

Just does a simple XOR on the ASCII values of the two chars and the lowest order bit determines which string to output.

Standalone executable DOS program (since STDIN/STDOUT is a requirement).

enter image description here

-1 byte thx to @l4m2!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ BA 0119 MOV DX, OFFSET L => MOV DL, L as they're in same 256B \$\endgroup\$
    – l4m2
    Commented Jan 8, 2023 at 13:08
2
\$\begingroup\$

Nibbles, 15 14 13 bytes

=+.@o$%`D-21~8fd905cff4e

Attempt This Online!

Explanation

   @                      - input
  . o$                    - as codepoints
 +                        - sum
=     %`D-21~8fd905cff4e  - index in compressed list ["light", "dark"] (wrapped)

-2 bytes thanks to Dominic van Essen

\$\endgroup\$
2
  • \$\begingroup\$ Nice! You can also save one byte (2 nibbles) using data to encode the "light" "dark" array: =%+.@o$2%`D-21~8fd905cff4e... \$\endgroup\$ Commented Jan 9, 2023 at 20:47
  • \$\begingroup\$ Also, Nibbles indexing wraps around by default, so you can leave-out the %2 altogether to save another byte: =+.@o$%`D-21~8fd905cff4e \$\endgroup\$ Commented Jan 10, 2023 at 9:49
2
\$\begingroup\$

Rattle, 32 bytes

dark&light&\|!I<gI0nr`gI1R1+\%b`

Try it Online!

Explanation

This essentially just takes the sum of the number and the ASCII value of the letter, sees if it's even or odd, and outputs "dark" or "light" accordingly.

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

Thunno 2 B, 9 bytes

S‘ɲ⁺/^‘½İ

Attempt This Online!

Explanation

S‘ɲ⁺/^‘½İ  # Implicit input, converted to ordinals by B flag
S          # Sum the list of ordinals of the input
 ‘ɲ⁺/^‘    # Push dictionary compressed string "lightdark"
       ½   # Halve it to get ["light", "dark"]
        İ  # 1-based modularly index the sum into this list
           # Implicit output
\$\endgroup\$
2
\$\begingroup\$

Go, 97 bytes

package main
import."os"
func main(){o:="light"
if(Args[1][0]+Args[1][1])%2<1{o="dark"}
print(o)}

Attempt This Online!

-3 byte improvement over @Kristoffer Sall-Storgaard's answer.

Takes input from command-line arguments. Prints to STDERR.

With more flexible IO format, 42 bytes

func(s string)int{return int(s[0]+s[1])%2}

Attempt This Online!

  • Use a function instead of a full program
  • Return a value instead of printing
  • Return an int (1 for "light", 0 for "dark") instead of a string
\$\endgroup\$
0
1
\$\begingroup\$

AHK, 78 bytes

a=%1%
If Mod(Asc(a)+Asc(SubStr(a,2)),2)=1
s=light
Else
s=dark
FileAppend,%s%,*

AHK uses 1 as the name for the first parameter so you have to assign to a different name before you use it in functions. Otherwise, it'll think you mean the value 1 and not the variable named 1. Also, the only way to report to STDOUT is by using FileAppend with * as the file name.

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

Chip, 57 bytes

*gS!~s
fA.Z\ZZZvt
cZ}x< eab
>--^/vZZvZZvt
ZZZd ddac ce
ab

Try it online!

XOR's the low bit of each input (like most if not all other answers) to make the decision. Outputs dabh`, bitwise-OR'd with hhe`t for light or ``pc for dark. (Dark also exits one byte early).

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

Japt, 16 bytes

`ä•Krk`qe g~Uxc

Try it online!

How it works

`ä•Krk`qe g~Uxc

`ä•Krk`          Compressed literal for "lightedark"
        qe        Split with "e"
           g      Take the element at the index (wrapping)...
             U      Input array of chars
              xc    Sum the chars' charcodes
            ~       Take bitwise not, in order to swap parity

The string array compression trick did quite a job here.

\$\endgroup\$
1
  • \$\begingroup\$ 15 bytes \$\endgroup\$
    – Shaggy
    Commented Oct 12, 2022 at 13:29
1
\$\begingroup\$

05AB1E (legacy), 13 bytes

“–°‡Ž“#I35öÈè

Try it online!

Here is a golf with your own language :)

Explanation

“–°‡Ž“       : compressed: "dark light"
      #      : split by space
            è: select the 0th or 1st element based on {
       I35ö  :  take the input and convert it to int from base 35
           È :  1 if even else 0
               }
\$\endgroup\$
1
\$\begingroup\$

Runic Enchantments, 25 bytes

iu+2%1(8*?"light"@"dark"@

Try it online!

How it works

>                      implicit entry
 i                     read string from input
  u                    break the string into characters
   +                   add them together
    2%                 modulo 2
      1(               compare with 1
        8*             multiply the result (true -> 8, false -> 0)
          ?            pop x, if x is truthy, skip x characters
           "light"@    output light if false
           "dark"@     ouput dark if true
\$\endgroup\$
1
\$\begingroup\$

Keg, 12 bytes

+2%[‘15‘|‘1⑻

Try it online!

A Keg port of Dennis' answer.

\$\endgroup\$
2
  • \$\begingroup\$ This is the obvious approach to a trivial question, so I wouldn't consider this a port (or am I missing something?) \$\endgroup\$ Commented May 24, 2020 at 7:37
  • \$\begingroup\$ I saw Dennis' answer and copied it. It uses the same algorithm as his answer, as in the explanation would pretty much be the same. \$\endgroup\$
    – lyxal
    Commented May 24, 2020 at 7:38
1
\$\begingroup\$

APL (Dyalog Unicode), 25 24 bytesSBCS

-1 thanks to Bubbler.

⊃'dark' 'light'⌽⍨+/⎕UCS⍞

Try it online!

 get text from stdin

⎕UCS convert to Universal Character Set code points

+/ sum

'dark' 'light'⌽⍨ use that to cyclically rotate the list of strings

 pick the first

\$\endgroup\$
4
  • \$\begingroup\$ 24 bytes. \$\endgroup\$
    – Bubbler
    Commented Feb 27, 2020 at 3:18
  • \$\begingroup\$ @Bubbler 23. \$\endgroup\$
    – Adám
    Commented Feb 27, 2020 at 6:17
  • \$\begingroup\$ OP requires a full program, so the 23 is invalid. \$\endgroup\$
    – Bubbler
    Commented Feb 27, 2020 at 6:20
  • \$\begingroup\$ @Bubbler Oh. Hm. \$\endgroup\$
    – Adám
    Commented Feb 27, 2020 at 6:21
1
\$\begingroup\$

05AB1E, 11 bytes

Port of Dennis's GS2 answer.

“–°‡Ž“#IÇOè

Try it online!

Explanation

“–°‡Ž“      Compressed string "dark light"
      #     Split on spaces
       I    Take an input
        Ç   Codepoints
         O  Sum
          è Modular index into the original list
\$\endgroup\$
1
\$\begingroup\$

Stax, 11 bytes

ĺÉ╨φr°mißâ

Run and debug it

Explanation

|+            Sum the codepoints of the input string
  `ASbEx!"`   Compressed string "dark light"
           j  Split on spaces. ["dark","light"]
            @ Fetch at the corresponding index (modular)
\$\endgroup\$
1
\$\begingroup\$

Python 3, 40 bytes

print('ldiagrhkt'[int(input(),35)%2::2])
\$\endgroup\$
1
\$\begingroup\$

Acc!!, 138 bytes

N+N
Count i while _%2 {
Write 108
Write 105
Write 103
Write 104
Write 116
0
}
Count i while _ {
Write 100
Write 97
Write 114
Write 107
0
}

Try it online!

Pseudocode

Read two characters, add their codepoints, and store the result in the accumulator
While the accumulator value is odd:
    Write l, i, g, h, t
    Set the accumulator to 0
While the accumulator value is nonzero:
    Write d, a, r, k
    Set the accumulator to 0
\$\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.