46
\$\begingroup\$

Here is a simple challenge for you: You must produce this ASCII representation of a chess board. White is represented by uppercase characters, and black is represented by lowercase. Empty tiles are represented by a .. Here is the full board:

rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

Since this is a question, you may not take any input and you must output this board by any default method, for example, saving a file, printing to STDOUT or returning from a function. You may optionally produce one trailing newline. Standard loopholes apply, and the shortest program in bytes!

However, remember this is equally as much a competition between submissions in the same language. While it's unlikely that a languages like Java could beat a language like perl, or a golfing language like pyth or cjam, having the shortest Java answer is still really impressive! To help you track the shortest answer in each language, you may use this leaderboard, which will show the shortest submission by language and overall.

Leaderboards

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=95745,OVERRIDE_USER=31716;function answersUrl(e){return"https://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"https://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\$
1
  • 2
    \$\begingroup\$ Surely an ASCII art chess board would have the full stop every other square? \$\endgroup\$ Sep 9, 2019 at 9:55

96 Answers 96

21
\$\begingroup\$

Vim, 26 bytes

irnbqkbnr<Esc>Y6p5Vr.VrpYGPgUj

Relies on a fresh Vim, or else 5V may select the wrong area.

  • irnbqkbnr<Esc>: Write the top row. Easy enough.
  • Y6p: Make the rest of the rows, except one. Of course all but the top and bottom rows contain the wrong characters.
  • 5Vr.: When you haven't used visual mode yet in the session, you can do things like this to select 5 lines. If you typed the same thing again right away, it would try to select 25 lines. Vim is weird like that.
  • Vrp: We're already on line 2, so let's make a pawn line.
  • YGP: Copy that pawn line into its place at the bottom. This is why I used 6p instead of 7p before.
  • gUj: Capitalize the white pieces.
\$\endgroup\$
1
16
\$\begingroup\$

Jelly, 25 24 bytes

“.“.“p“rnbqkbn”ṁ€8µṚ;ŒuY

Try it online!

Thanks to @Lynn for golfing off 1 byte!

How it works

“.“.“p“rnbqkbn”ṁ€8µṚ;ŒuY  Main link. No arguments.

“.“.“p“rnbqkbn”           Yield [".", ".", "p", "rnbqkbnr"].
               ṁ€8        Mold-each 8; reshape each string like the array
                          [1, 2, 3, 4, 5, 6, 7, 8], i.e., cyclically repeat its
                          contents to create strings of length 8.
                          This yields the upper half of the board in reversed
                          order, i.e., the string array
                          A := "........", "........", "pppppppp", "rnbqkbnr"].
                  µ       Begin a new, monadic chain. Argument: A
                   Ṛ      Reverse A.
                     Œu   Convert all characters in A to uppercase.
                    ;     Concatenate the results to both sides.
                       Y  Join the strings, separating by linefeeds.
\$\endgroup\$
0
12
\$\begingroup\$

Brainfuck, 224 bytes

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

Took almost an hour to get this.

\$\endgroup\$
9
\$\begingroup\$

Python 2, 63 bytes

print"\n".join(["rnbqkbnr","p"*8]+["."*8]*4+["P"*8,"RNBQKBNR"])

Unfortunately, the fairly simple approach was much shorter than the "clever" stuff I tried at first...

Bonus answer, also 63 bytes:

print"\n".join(["rnbqkbnr"]+[c*8for c in"p....P"]+["RNBQKBNR"])
\$\endgroup\$
1
9
\$\begingroup\$

05AB1E, 24 bytes

Uses CP-1252 encoding.

"rnbqkbnr"'p8×'.8×D)Âu«»

Try it online!

Explanation

"rnbqkbnr"                # push the string "rnbqkbnr"
                          # STACK: "rnbqkbnr"
          'p8×            # push the char "p" repeated 8 times
                          # STACK: "rnbqkbnr", "pppppppp"
              '.8×        # push the char "." repeated 8 times
                          # STACK: "rnbqkbnr", "pppppppp", "........"
                  D       # duplicate
                          # STACK: "rnbqkbnr", "pppppppp", "........", "........"
                   )      # wrap in list
                          # STACK: ["rnbqkbnr", "pppppppp", "........", "........"]
                    Â     # push a reversed copy of the list
                          # STACK: ["rnbqkbnr", "pppppppp", "........", "........"], 
                                   ["........", "........", "pppppppp", "rnbqkbnr"]
                     u«   # convert to upper-case and concatenate
                          # STACK: ['rnbqkbnr', 'pppppppp', '........', '........', 
                                    '........', '........', 'PPPPPPPP', 'RNBQKBNR']
                       »  # join list by newline
\$\endgroup\$
3
  • 2
    \$\begingroup\$ I think this is the FIRST time I've ever golfed an answer without looking and matched you on 100% of the characters used. Gotta agree this is as good as it gets haha. \$\endgroup\$ Feb 10, 2017 at 20:23
  • \$\begingroup\$ I realize this might not have been available when you posted it, but -2 by compressing the string to .•jÒ°\Ö• and another -2 by using the list-prepend š like this: …p..S8×.•jÒ°\Ö•šÂu«». Or alternatively: …p...•jÒ°\Ö•š8δ∍Âu«». \$\endgroup\$ Feb 5, 2020 at 12:25
  • \$\begingroup\$ Based on my second solution above, here also a 23 byter without the compressed string that most likely was also possible when you posted your solution: "rnbqkbnr"'p'.D)8δ∍Âu«» (@MagicOctopusUrn) \$\endgroup\$ Feb 5, 2020 at 12:34
7
\$\begingroup\$

Actually, 26 bytes

'p8*"rnbqkbnr"│û@û4'.8*n((

Try it online!

Explanation:

'p8*"rnbqkbnr"│û@û4'.8*n((
'p8*                        "p"*8 ["pppppppp"]
    "rnbqkbnr"              that string ["rnbqkbnr", "pppppppp"]
              │             duplicate stack ["rnbqkbnr", "pppppppp", "rnbqkbnr", "pppppppp"]
                û@û         uppercase the dupes ["RNBQKBNR", "PPPPPPPP", "rnbqkbnr", "pppppppp"]
               4   '.8*n    "."*8, 4 times ["RNBQKBNR", "PPPPPPPP", "........", "........", "........", "........", "rnbqkbnr", "pppppppp"]
                        ((  move the uppercase strings to the bottom of the stack, implicitly print
\$\endgroup\$
7
\$\begingroup\$

PowerShell v2+, 44 bytes

'rnbqknbr'
'p'*8
,('.'*8)*4
'P'*8
'RNBQKNBR'

Strings left on the pipeline are implicitly printed with Write-Output at program execution. We couple that with the default newline behavior for an array to produce the four lines of periods with the comma-operator.

PS C:\Tools\Scripts\golfing> .\draw-ascii-chess-board.ps1
rnbqknbr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKNBR
\$\endgroup\$
2
  • \$\begingroup\$ Where are the new lines in the lines of points? " ,('.'*8)*4" it is the ',' I suppose... \$\endgroup\$
    – user58988
    Oct 11, 2016 at 15:48
  • \$\begingroup\$ @RosLuP The comma-operator ,, creates an array (in this case, an array of strings). The default Write-Output at program completion inserts a newline between elements left on the pipeline, including individual array elements. So, we're abusing the default output behavior to not need to write explicit newlines in the code. \$\endgroup\$ Oct 11, 2016 at 15:52
7
\$\begingroup\$

Ruby, 45 44

1 byte saved thanks to tuxcrafting.

puts"rnbqkbnr",?p*8,[?.*8]*4,?P*8,"RNBQKBNR"

This is 45

puts s="rnbqkbnr",?p*8,[?.*8]*4,?P*8,s.upcase

Trying anything cleverer just seems to make it longer.

\$\endgroup\$
1
  • \$\begingroup\$ Remove the space before the string after the puts \$\endgroup\$ Oct 10, 2016 at 17:33
7
\$\begingroup\$

JavaScript (ES6), 69 65 bytes

Saved 4 bytes thanks to edc65

let f =

_=>`rnbqkbnr
p....PRNBQKBNR`.replace(/p|\./ig,c=>c.repeat(8)+`
`)

console.log(f());

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Very clever! Maybe too clever, could save 4 bytes with 'rnbqkbnrnp....PRNBQKBNR'.replace(/p|\./ig,c=>c.repeat(8)+'\n') (change \n to a literal newline) \$\endgroup\$
    – edc65
    Oct 10, 2016 at 19:35
6
\$\begingroup\$

Cheddar, 56 bytes

a=['rnbqkbnr','p'*8]+['.'*8]*2->(a+a.rev=>@.upper).vfuse

Uses the new => feature.

Explanation

a=                      // set a to the first half
  ['rnbqkbnr','p'*8] +  // First two rows
  ['.'*8]*2             // Next two dots
->(
   a +
   a.rev=>@.upper       // Reverse and map all items to uppercase
).vfuse                 // Join on newlines
\$\endgroup\$
3
  • 5
    \$\begingroup\$ So you answered a question about 'chess' in 'ches'? \$\endgroup\$
    – DJMcMayhem
    Oct 10, 2016 at 2:51
  • 4
    \$\begingroup\$ @DJMcMayhem .................. did you just..... \$\endgroup\$
    – Downgoat
    Oct 10, 2016 at 2:52
  • 1
    \$\begingroup\$ mm this is some beautiful cheese. nice abuse of default params \$\endgroup\$ Oct 10, 2016 at 3:03
6
\$\begingroup\$

Pyke, 28 27 26 bytes

"rnbqkbnr"i"P..p"1c8m*Xil3

Try it here!

I learned something new about my language today: 1c can be used as a 2 char way of splitting a string into a list of characters.

"rnbqkbnr"i                - i = "rnbqkbnr"
                             stack = ["rnbqkbnr"])
           "P..p"1c        -  chunk("P..p", 1)
                             stack = ["rnbqkbnr", ["P", ".", ".", "p"]]
                   8m*     - map(8*>, ^)
                             stack = ["rnbqkbnr", ["PPPPPPPP", "........", "........", "pppppppp"]]
                      X    - splat(^)
                             stack = ["rnbqkbnr", "pppppppp", "........", "........", "PPPPPPPP"]
                       il3 - i.changecase()
                             stack = ["rnbqkbnr", "pppppppp", "........", "........", "PPPPPPPP", "RNBQKBNR"]
                           - implicit join with newlines

rnbqkbnr
pppppppp
........
........
PPPPPPPP
RNBQKBNR
\$\endgroup\$
6
\$\begingroup\$

C#, 94 92 bytes

Edit: Thanks to milk for saving 1 byte by changing string order to remove the return whitespace.

Edit: Saved 1 more byte by adding a dummy parameter (x instead of ()) for the anonymous function and calling it with any object.

x=>{string a="RNBQKBNR\n",b="PPPPPPPP\n",c="........\n";return(a+b).ToLower()+c+c+c+c+b+a;};

Full program using the above function:

using System;

namespace DrawAnASCIIChessBoard
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<object,string>f= x=>{string a="RNBQKBNR\n",b="PPPPPPPP\n",c="........\n";return(a+b).ToLower()+c+c+c+c+b+a;};
            Console.WriteLine(f(1));
        }
    }
}

C# is a very verbose language...


C# full program, 131 bytes

class P{static void Main(){string a="rnbqkbnr\n",b="pppppppp\n",c="........\n";System.Console.Write(a+b+c+c+c+c+(b+a).ToUpper());}}

Ungolfed:

class P
{
    static void Main()
    {
        string a="rnbqkbnr\n",
            b="pppppppp\n",
            c="........\n";
        System.Console.Write(a+b+c+c+c+c+(b+a).ToUpper());
    }
}
\$\endgroup\$
6
  • 2
    \$\begingroup\$ "C# is a very verbose language...". You haven't tried VB.NET then... ;) \$\endgroup\$
    – TyCobb
    Oct 10, 2016 at 17:06
  • 2
    \$\begingroup\$ You can save a byte by defining a and b as uppercase then you can get rid of the space after return: return(a+b).ToLower()+... \$\endgroup\$
    – milk
    Oct 10, 2016 at 19:15
  • \$\begingroup\$ @TyCobb I tried VB.NET quite some time ago. I didn't know about code golfing back then :P \$\endgroup\$
    – adrianmp
    Oct 10, 2016 at 19:42
  • \$\begingroup\$ can you use var instead of string ? \$\endgroup\$
    – NibblyPig
    Oct 11, 2016 at 11:27
  • 1
    \$\begingroup\$ @SLC I haven't programmed in C# for a while, so correct me if I'm wrong, but I don't think you can use var with multiple declarations on a single line. So string a="rnbqkbnr\n",b="pppppppp\n",c="........\n"; would become var a="rnbqkbnr\n";var b="pppppppp\n";var c="........\n";, which increases the byte-count. EDIT: It would give an "An implicitly typed local variable declaration cannot include multiple declarators" error. \$\endgroup\$ Oct 11, 2016 at 12:07
6
\$\begingroup\$

Commodore BASIC V2/V7 (Commodore C64/128, VIC-20, TheC64Mini) - 129 tokenized and BASIC bytes

 0n$=cH(13):a$="{clear}{ctrl+h}{ctrl+n}rnbqkbnr"+n$:p$="pppppppp"+n$:?a$p$;:fOi=0to3:?"........":nE:goS1:?p$a$:end
 1a$="RNBQKBNR"+n$:p$="PPPPPPPP"+n$:reT

This should be entered into BASIC on a Commodore 128 and saved, it will then load into the VIC/C64 okay (you may need LOAD "CHESS",8,0 on the VIC-20), or use CBM PRG Studio. The reason for this is that I'm going over the 80/88 character limit in line 0 for the C64/VIC-20 respectively. The C128 allows a 160 PETSCII character limit, so with keyword abbreviations this could easily be > 160 character per BASIC line.

The {clear} character is achieved by SHIFT + CLR/HOME, whereas (in a string) CTRL+H disables the SHIFT+C= key to toggle between graphics and business mode, and CTRL+N changes the case to business mode in BASIC.

The resulting listing is as in the screen shot. Copy the listing above and paste it into WinVICE with a right-click on your mouse over the VICE window.

I've added the resulting output on the VIC-20 to prove that it'll load on that mighty micro as well.

Commodore 128 BASIC listing of PETSCII art chess board VIC-20 PETSCII chess board simulator

\$\endgroup\$
5
\$\begingroup\$

Haskell, 53 bytes

a="rnbkqbnr" 
unlines$a:map(<$a)"p....P"++["RNBKQBNR"]

a is used as the first line and to determine the length of strings made of p, . and P (-> <$a). .

\$\endgroup\$
5
\$\begingroup\$

MATL, 26 bytes

'rnbqkbnr' 'p..'!l8X"vtPXk

Try it online!

Explanation

'rnbqkbnr'   % Push this string (1×8 char array)
'p..'!       % Push this string transposed (3×1 char array)
l8X"         % Repeat 1×8 times: gives 3×8 char array
v            % Concatenate the two arrays vertically into a 4×8 char array
tP           % Duplicate and flip vertically
Xk           % Convert to uppercase. Implicitly display the two 4×8 arrays
\$\endgroup\$
5
\$\begingroup\$

J, 34 bytes

(tolower,|.)4 8$'RNBQKBNR',8#'P..'

Try it online!

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

Python 2, 68 bytes

Posting anyway although the above Python 2 version is shorter. It would not have to be a one liner for the amount of bytes, just played with it.

x,y,z="rnbqkbnr\n","p"*8+"\n","."*8+"\n";print x,y,4*z,(y+x).upper()
\$\endgroup\$
1
  • \$\begingroup\$ Since z is only used once you can get rid of it and produce the dots in the print statement. \$\endgroup\$
    – Karl Napf
    Oct 14, 2016 at 1:59
4
\$\begingroup\$

JavaScript (ES6), 73

.toUpperCase is simply too long

_=>`rnbqkbnr
${r=c=>c[0].repeat(8)+`
`,r`p`+(b=r`.`)+b+b+b+r`P`}RNBQKBNR`

O.textContent=(
  
_=>`rnbqkbnr
${r=c=>c[0].repeat(8)+`
`,r`p`+(b=r`.`)+b+b+b+r`P`}RNBQKBNR`

)()
<pre id=O></pre>

\$\endgroup\$
3
  • \$\begingroup\$ I think (r=c=>c[0].repeat(8)+\n,b=r.)=> saves you a byte. \$\endgroup\$
    – Neil
    Oct 10, 2016 at 8:43
  • \$\begingroup\$ @Neil I don't see the saving. I tried to rewrite the code increasing readibility (a little), but the byte count stay the same \$\endgroup\$
    – edc65
    Oct 10, 2016 at 9:23
  • \$\begingroup\$ Ah, I see what I did wrong there, somehow I lost a newline along the way. Sorry about that. \$\endgroup\$
    – Neil
    Oct 10, 2016 at 9:45
4
\$\begingroup\$

V, 27, 26 bytes

i¸P
RNBQKBNRäkgujddppÒ.4Ä

Try it online!

This contains some unprintable characters, so here is the readable version:

i¸P
RNBQKBNR<esc>äkgujddppÒ.4Ä

where <esc> represents 0x1B. Explanation:

i                               " Enter insert mode
 ¸P                             " Enter 8 'P' characters
                                " and a newline
RNBQKBNR<esc>                   " Enter the first row and escape to normal mode.
             äk                 " Duplicate this line and the line above
               guj              " Convert this line, and the line below to lowercase
                  dd            " Delete this line
                    pp          " And paste it twice below us
                      Ò.        " Replace this whole line with '.' chars
                        4Ä      " And create four copies of this line
\$\endgroup\$
4
\$\begingroup\$

Emotinomicon, 89 bytes

Sadly Emotinomicon has nothing like an duplicate stack function. Would be usefull. But at least shorter than Java. :)

😭RNBKQBNR
PPPPPPPP
........
........
........
........
pppppppp
rnbkqbnr😲⏪⏬⏩

Explanation:

😭(...)😲⏪⏬⏩
😭(...)😲            String literal
         ⏪  ⏩      Loop
           ⏬        Pop one char and output
\$\endgroup\$
2
  • \$\begingroup\$ Hmm... that would be a useful function, now wouldn't it... \$\endgroup\$ Oct 14, 2016 at 1:00
  • 3
    \$\begingroup\$ Even the program is sad. 😭 = Sadly \$\endgroup\$
    – user85052
    Sep 13, 2019 at 6:16
4
\$\begingroup\$

Python 3.5, 56 bytes

for r in['rnbqkbn',*'p....P','RNBQKBN']:print((r*8)[:8])

This uses an idea by zawata to encode each line as (r*8)[:8], with a string repeated 8 times and trimmed to length 8. The pawns and empty rows are just 'p'*8, '.'*8, and 'P'*8, with no trimming. The first row uses 'rnbqkbn', with ('rnbqkbn'*8)[:8] including another rook on the right when multiplied and trimmed. The last row is the same but capitalized.

We express the list of row-parts compactly ['rnbqkbn','p','.','.','.','.','P','RNBQKBN'] using Python 3.5's generalized unpacking. We write out the first and last-entries, and the remaining single-character ones are unpacked from a string.

In Python 2, we could settle for split instead for 60 bytes:

for i in'rnbqkbn p . . . . P RNBQKBN'.split():print(i*8)[:8]
\$\endgroup\$
4
\$\begingroup\$

C, 87 bytes

#define E "........\n"
main(){puts("rnbqkbnr\npppppppp\n"E E E E"PPPPPPPP\nRNBQKBNR");}

This uses preprocessor and string literal joining. Sorry, Matthew Greci and CSM, I don't have any reputation here to comment on your solution

\$\endgroup\$
4
+100
\$\begingroup\$

Vyxal J, 26 24 31 28 25 bytes

-2 bytes thanks to the j flag.
+7 bytes, added code to swap Q and K to make it valid.
-3 bytes thanks to Aaron Miller!
-3 bytes thanks to Kevin Cruijssen

«æ≠⁺tO«\p8*\.8*:W⁋Ḃ⇧‛KQḂV

Explanation

«æ≠⁺tO«                         - Push "rnbqkbnr"
       \p8*                     - Push "pppppppp"
           \.8*:                - Push "........" twice
                W⁋              - Listify, then join by \n
                  Ḃ⇧            - Bifurcate and uppercase the second half
                    ‛KQḂV       - Replace "KQ" with "QK"
<flag>                          - Join by newlines and print entire stack implicitly

Try it Online!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ This is invalid, the QK are in the wrong places. \$\endgroup\$
    – emanresu A
    Sep 8, 2021 at 12:39
  • \$\begingroup\$ @emanresuA It should be valid now. \$\endgroup\$ Sep 8, 2021 at 13:02
  • 1
    \$\begingroup\$ 28 bytes \$\endgroup\$ Sep 8, 2021 at 13:19
  • 1
    \$\begingroup\$ 25 bytes (note the J as flag instead of j) \$\endgroup\$ Sep 8, 2021 at 15:13
3
\$\begingroup\$

Powershell, 82 73 bytes

$x=("rnbqkbnr",$("p"*8),$("."*8),$("."*8));$x+$x[3..0].ToUpper()-join"`n"
\$\endgroup\$
4
  • 1
    \$\begingroup\$ 59 bytes \$\endgroup\$
    – Veskah
    Jul 8, 2019 at 19:56
  • 1
    \$\begingroup\$ @Veskah - how does that work? I've not seen the *per thing before, and a google isn't giving me any pointers. Have an explanation? \$\endgroup\$
    – Chris J
    Jul 9, 2019 at 22:08
  • 1
    \$\begingroup\$ Check here for the full writeup but |% can call properties/methods (with wildcards in the name) on what it's given \$\endgroup\$
    – Veskah
    Jul 10, 2019 at 0:39
  • \$\begingroup\$ Using Veskah's trick and some ideas from other languages here, I got it down to 52: $a="rnbqkbnr",('p'*8)+@('.'*8)*4;$a+($a[1,0]|% *per). I'm hooked. Thanks Veskah! (And Chris J), learned something new today! \$\endgroup\$
    – Lockszmith
    Sep 7, 2021 at 6:59
3
\$\begingroup\$

GNU sed, 54 bytes

s:^:rnbqkbnr:p;h
s:.:p:gp;G
h;s:[^\n]:.:gp;G
s:.:\U&:g

Try it online!

Explanation:

The black pieces are printed first, saving the two associated board ranks in reverse order in the hold space. The white pieces are printed by converting the hold space to uppercase letters.

s:^:rnbqkbnr:p;h   # change pattern and hold spaces to 'rnbqkbnr' and print string
s:.:p:gp           # replace each pattern space letter with a 'p', then print
G;h                # append hold space, then copy pattern space to hold space
s:[^\n]:.:gp       # replace each pattern space letter with a '.', then print
G;s:.:\U&:g        # append hold space and convert pattern space to uppercase
                   # (automatic printing of pattern space at the end)
\$\endgroup\$
3
\$\begingroup\$

Brain-Flak, 366 350 + 3 = 353 bytes

Try it online!

(((((((((((()()())){}(((({}))){}{}(([((({})){}){}](([({}())](((((({}()){}){}){}()){})<>))<>)<>)<>)))<<>({}<>)<>({}<>)<>({}<>)([]()())>[()]))))))))(()()()()){({}[()]<((((((((((((()()()()()){})()){}()){}))))))))>)}{}(((()()()()()){})<((((((((([][]()()()()))))))))<>)<>>)(((((()()()))){})(({}{})(([{}({})](([{}()](<>({}()())<>)<>)<>)<>)<>))){<>({}<>)}{}

This gets a plus 3 because it requires the -A flag to run properly.

Explanation

First we push the last 5 letters to the active stack.
We also push copies of last 3 numbers to the inactive stack.
This is done with fairly simple methods I won't go into for the sake of brevity.

 (((()()())){}(((({}))){}{}(([((({})){}){}](([({}())](((((({}()){}){}){}()){})<>)<><>)<>)<>)<>)))

We Move Everything from the offstack to the onstack.
The first 3 letters are the same as the last 3 letters in the first line

{<>({}<>)}{}

We push 10 for a new line

((()()()()()){})

Using the value of Q we create a P and push it 8 times

((((((((<...>[()]))))))))

We loop 4 times each time pushing 8 dots and a newline

(()()()())
{({}[()]<
    ((((((((((((()()()()()){})()){}()){}))))))))
>)}{}

We push the last two lines in a very similar way to the first two.

(((()()()()()){})<((((((((([][]()()()()))))))))<>)<>>)(((()()()){})(({}()()())(([{}(()()())](([{}()](<>({}()())<>)<>)<>)<>)<>))){<>({}<>)}{}
\$\endgroup\$
1
  • \$\begingroup\$ You can push the first two lines with ((((((((((((((((((((()()()()()){}){}){}()){})[()()()()])[([][][]){}])[][][])[]()())[[][][]])[][])()()()())<([]()())>[()()])))))))) which I think would save you 16 bytes. This doesn't use the alternate stack at all, so it could probably be even shorter. \$\endgroup\$
    – DJMcMayhem
    Oct 19, 2017 at 17:40
3
\$\begingroup\$

Python 3, 82 80 75 Bytes

Not the shortest answer in python but it's my first and i think its pretty good for a first time

print('\n'.join((i*8)[:8]for i in'rnbqkbn p . . . . P RNBQKBN'.split()))
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Welcome to the site! You could take two bytes off if you remove some extra spaces. E.g. [:8]for i in['rnbqkbn'.... \$\endgroup\$
    – DJMcMayhem
    Oct 12, 2016 at 2:14
  • 1
    \$\begingroup\$ Nice idea with unifying all the lines and reusing the rooks. You can write the list shorter as 'rnbqkbn p . . . . P RNBQKBN'.split(). \$\endgroup\$
    – xnor
    Oct 12, 2016 at 2:23
  • \$\begingroup\$ @DJMcMayhem didn't know those weren't necessary. thanks! \$\endgroup\$
    – zawata
    Oct 12, 2016 at 6:02
  • \$\begingroup\$ @xnor that is a great idea! ill have to add that trick to my "arsenal" haha \$\endgroup\$
    – zawata
    Oct 12, 2016 at 6:02
3
\$\begingroup\$

C, 112 109

char *e="rnbqkbnr";main(a){for(;a<65;)putchar((a++-1)%9?a<11?e[a-3]:a<20?112:a<48?46:a<57?80:e[a-57]-32:13);}

Readable:

char *e="rnbqkbnr";
main(a){
    for(;a<65;)
        putchar((a++-1)%9?a<11?e[a-3]:a<20?112:a<48?46:a<57?80:e[a-57]-32:13);
}

Notes:
•char 13 = new line
•char 112 = 'p'
•char 46 = '.'
•char 80 = 'P'
•lowercase char-32 = UPPERCASE CHAR

Thoughts: It's annoying because this is very well golfed for a short solution, but at the same time I could have gone sub-100 in my byte count by just hard coding in most of the chess board and just repeating the . . . part with a puts loop. But that's a very boring answer


Thanks @Ahemone for 3 bytes off!

\$\endgroup\$
4
  • \$\begingroup\$ You may remove ==0 from the first ternary and swap the return arguments to save 3 bytes \$\endgroup\$
    – Ahemone
    Feb 15, 2017 at 4:36
  • \$\begingroup\$ @Ahemone oh you're right! Rookie mistake haha \$\endgroup\$ Feb 15, 2017 at 5:06
  • 1
    \$\begingroup\$ 101 bytes \$\endgroup\$
    – ceilingcat
    Apr 24, 2019 at 21:49
  • \$\begingroup\$ I feel your pain. I had similarly golfed to 117 with a fancy algorithm (you beat me there) only to realize a straight puts beat it handily. \$\endgroup\$ Jun 17, 2020 at 20:32
3
\$\begingroup\$

x86-64 Machine Code, 81 bytes

57                   push        rdi  
48 BA 52 4E 42 4B 51 42 4E 52 mov         rdx,524E42514B424E52h
52                   push        rdx  
BA 50 50 50 50       mov         edx,50505050h  
52                   push        rdx  
89 54 24 04          mov         dword ptr [rsp+4],edx  
51                   push        rcx  
5A                   pop         rdx  
6A 30                push        30h  
59                   pop         rcx  
48 2B E1             sub         rsp,rcx  
54                   push        rsp  
5F                   pop         rdi  
B0 2E                mov         al,2Eh  
F3 AA                rep stos    byte ptr [rdi]  
0F 10 44 24 30       movups      xmm0,xmmword ptr [rsp+30h]  
0F 11 04 24          movups      xmmword ptr [rsp],xmm0  
54                   push        rsp  
52                   push        rdx  
56                   push        rsi  
5A                   pop         rdx  
5F                   pop         rdi  
5E                   pop         rsi  
B1 10                mov         cl,10h  

80 74 8C FF 20       xor         byte ptr [rsp+rcx*4-1],20h  
E2 F9                loop        addLoop (07FF66A5A13B8h)  
B1 08                mov         cl,8  
B0 0A                mov         al,0Ah  

48 A5                movs        qword ptr [rdi],qword ptr [rsi]
AA                   stos        byte ptr [rdi]  
E2 FB                loop        addLoop+0Bh (07FF66A5A13C3h)  
C6 07 00             mov         byte ptr [rdi],0  
48 83 C4 40          add         rsp,40h  
48 8B F2             mov         rsi,rdx  
5F                   pop         rdi  
C3                   ret  

Create using abuse of push/pop instructions. Could probably save a few bytes by using Linux calling conventions. Outputs to a pointer specified in the first parameter rcx.

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

Python 3, 59 bytes

print('rnbqkbnr','p'*8,*['.'*8]*4,'P'*8,'RNBQKBNR',sep='\n')

Interesting that with better unpacking and print function, Python 3 can be much better than Python 2 for golf

This was based on https://codegolf.stackexchange.com/a/95758/2212

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.