32
\$\begingroup\$

figure and ground
Source: Wikipedia

For this challenge, you should write two programs which resemble the figure and ground of the above image, such that one of them prints figure and the other prints ground. Specifically:

  1. Write a program which takes no input and prints the string figure. The only allowed whitespace characters in your program are spaces (code point 0x20) and newlines (carriage returns, 0x0D, linefeeds, 0x0A, or a combination of both).
  2. Ignoring the newlines, the number of space characters (code point 0x20) and non-space characters has to be the same. For example, this would be a valid program (in a hypothetical language):

    ab c 
       d
    e f
    

    Note that there is a trailing space on the first line.

  3. If you swap the nth space character with the nth non-whitespace character, the program should print ground instead. For the above example the program would look like this:

      a b
    cde 
     f 
    

    Note that there are trailing spaces on the second and third lines.

Both the figure and the ground solutions should be full programs in the same language which print to STDOUT. You may print a single optional trailing newline in either case. You may output anything you want to STDERR, as long as STDOUT is correct.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in bytes – wins.

Helper Script

You can use this CJam script to convert between a figure and ground program. Simply paste one of the two into the Input field and run the program. It will also tell you if there the number of spaces and non-spaces doesn't match up.

Leaderboard

function answersUrl(a){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"http://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&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(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.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(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery("<a>"+g+"</a>").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101275,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=8478,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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:350px;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="language-list"> <h2>Shortest Solution 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><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><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\$
0

20 Answers 20

20
\$\begingroup\$

Jelly, 20 bytes

Figure

“¦ĠȮ“©ụd» Ṃ         

Nine trailing spaces. Try it online!

Ground

         “ ¦ĠȮ“©ụd»Ṃ

No trailing spaces. Try it online!

How it works

First, note that spaces aren't atoms, so the space characters outside the string literals do not affect the program in any way.

The string literals use Jelly's built-in dictionary-based string compression to produce the desired words. A compressed string literal begins with , ends with », and uses internally to create an array of strings.

In the figure program, “¦ĠȮ“©ụd» yields the string pair (“figure”, “ground”), and the atom selects the lexicographical minimum, i.e., “figure”.

In the ground program, “ ¦ĠȮ“©ụd» yields the string pair (“logicallyAbacs”, “ground”) instead. The lexicographical minimum is now “ground”, which selects dutifully.

In both cases, the interpreter automatically prints the last return value – i.e., the selected minimum – to STDOUT.

\$\endgroup\$
0
14
\$\begingroup\$

Python 2, 53 bytes

Replace · with space in both answers:

····················
print'······figureground'[6:12]#

Prints figure.

print'figureground'[
······6:12]#····················

Prints ground.

\$\endgroup\$
14
\$\begingroup\$

05AB1E, 15 14 bytes

Figure

 'ŠÂ,'í¶      

Try it online!

Ground

'       ŠÂ,'í¶

Try it online!

Uses the CP-1252 encoding. Note the trailing spaces. In the Figure program, it's a normal program without errors. It decompresses the following words:

'ŠÂ  ->  figure
'í¶  ->  ground

The comma prints pops and prints the figure word with a newline. Since something has been printed, the top of stack is not printed anymore.

In the Ground program, there are some errors which is convenient in this case. The following part:

'<space>

pushes a space character on top of the stack. The Š rotates the stack, which has an arity 3. There is just one element on the stack and no input, so this gives an exception, clearing the stack. The  bifurcates the top of the stack, but this has the same story as the rotate operator. So basically the , command prints nothing.

That means that the program will still output the top of the stack which is 'í¶. Resulting into ground.

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

Retina, 31 bytes

Figure:

|       
figure
 |ground
      

Ground:

 |figure

|       
ground

Figure and Ground. Both programs require that STDIN be left empty to be valid figure or ground programs.

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

Pyth, 30 bytes

Figure

"figure" "ground              

14 trailing spaces.

Test

Ground

No trailing spaces

        "       figure""ground

Test

How it works

Rather helpfully, a space supresses printing in Pyth, while string literals with no closing " are implicitly closed.

The first program therefore consists of two strings, "figure" and "ground ". The first string is implicitly printed, and the printing of the second is supressed, meaning that just figure is printed.

The second program consists of two strings, " figure" and "ground". The printing of the first is supressed, and the second is implicitly printed, meaning that just ground is printed.

\$\endgroup\$
6
\$\begingroup\$

MATL, 37 bytes

First program

'figure'         
%x'ground'         

Each line has 9 trailing spaces.

Try it online!

Second program

    'figure'%
      x'ground'

There are no traling spaces here.

Try it online!

Explanation

Nothing terribly fancy...

  • Spaces and newlines between statements are ignored by MATL.
  • % is the comment symbol, which ignores the rest of the line.
  • x deletes the top of the stack.
  • The stack is implicitly printed at the end of the program.
\$\endgroup\$
6
\$\begingroup\$

Java, 180 bytes

Replace . with space.

Prints "figure":

class
A{public
static
void
main(String[]a){System.out.println(
//"ground"
//
.....
........
......
....
...................................
..
........
..........
....
"figure");}}

Prints "ground":

.....
........
......
....
...................................
..........
..
class
A{public
static
void
main(String[]a){System.out.println(
//
"ground"
//"figure"
);}}
............
\$\endgroup\$
5
\$\begingroup\$

Befunge, 54 bytes

Figure (Try it online!)

#v "erugif"v          >
      :#,_@>         
"dnuorg"

Ten trailing spaces on the second line.

Ground (Try it online!)

  #         v"erugif"v 
>:#,_@      >"dnuorg"
        

One trailing space on the first line and eight spaces on the third line.

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

Mathematica, 50 34 bytes

Uses a REPL environment. (Adding a Print[] wrapper with an equal number of spaces would increase the byte count by 14.) The two programs are

01figure+0 1ground                

(with 16 trailing spaces) and

          0       1figure+01ground

The key here is that Mathematica treats digit concatentation without spaces as a single number, but intervening spaces are interpreted as neighborly multiplication, as is the concatenation of numbers and arbitrary variable names. So the first expression evaluates to 1*figure+0*1*ground, which is figure; the second expression evaluates to 0*1*figure+1*ground, which is ground.

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

PHP, 44 42 bytes

figure: (16 trailing spaces, 5 spaces between figure & ;)

echo''?ground:figure     ;                 

ground: (20 leading spaces)

                     echo' '?ground:figure;

Pretty simple really, works because '' is falsey and ' ' is truthy. Use like:

php -r "echo''?ground:figure     ;                "
php -r "                    echo' '?ground:figure;"

edit: 2 retrospectively obvious bytes saved thanks to Martin Ender

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

Haskell, 96 94 88 82 77 bytes

First program, prints "figure":

main              =          putStr$idid"ground"
idid    _          ="figure"

Second program, prints "ground":

    main=putStr$id id"ground"                   
    idid _="figure"         

Calls one of two differently named constant functions

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

Haskell, 88 65 bytes

main=putStr
...........--
.."figure"..........
--"ground"........

and

...........
main=putStr..
--........"figure"--
.........."ground"

. indicates a space. Just some line comment (-> --) juggling.

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

Python 2, 52 bytes

........................
print"figure"
an
d
"ground"

.s indicate spaces. The last three lines are split up to error out without having a SyntaxError which would prevent the code from running in the first place.

The ground version just uses and to make the second string be printed.


Alternative (longer) attempts:

.......
print(#"ground")#
"figure")...................


print"figure"""and"ground"
.............
.............
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 56 bytes

alert('figure'
                //&&'ground'
           )
              
alert('figure'//            
&&'ground') 

The figure has no trailing spaces.

\$\endgroup\$
2
  • \$\begingroup\$ I count 56 bytes for each program, unless the newlines don't count. I doubt it will get any shorter. \$\endgroup\$ Nov 29, 2016 at 2:44
  • \$\begingroup\$ @ETHproductions Ugh, that's what happens when you count bytes manually :-( \$\endgroup\$
    – Neil
    Nov 29, 2016 at 8:56
2
\$\begingroup\$

Rail, 56 bytes

Figure

$'main'
 -[figure]o                
-          [ground]o

There are 16 trailing spaces on the second line. The program terminates with an error.

Try it online!

Ground

       
$          'main'-[figure]o
 -[ground]o         

There are 7 spaces on the first line and 9 trailing spaces on the last line. This program also terminates with an error.

Try it online!

Explanation

Rail looks for a line starting with (regex notation) \$.*'main' to find an entry point. The train (instruction pointer) then starts from the $ moving south-east. Things that aren't reachable by the train can be ignored completely for the program. This includes anything on the same line as the entry point. Since, the - south-east of the $ immediately turns the train east, both programs simply reduce to:

 -[figure]o
 -[ground]o

[...] denotes a string literal and o prints it. Normally, you need a # to end the rail, but if you omit it, the program terminates anyway (but complains on STDERR that the train crashed).

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

><>, 39 bytes

Using · to represent spaces.

Figure

v·
"·dnuo
e·
r·
u·
g··
i··
f···
"·
>·o·

Try it online!

Ground

·v
·"····
·d
·n
·u
·oe
·ru
·gif
·"
·>·o

Try it online!

Both programs terminate with an error.

Explanation

By writing the code vertically, I was able to reuse the g and the r between both solutions, as well as the quotes and the > and o for the output loop.

In both cases, the only bit that gets executed is the column below the v, which pushes the letters of the required word onto the stack in reverse order. Then > redirects the instruction pointer to the right, where it loops through the o, printing the characters until the stack is empty.

\$\endgroup\$
3
  • \$\begingroup\$ I just started working on my own ><> version, then I came across yours. I really like the idea of yours working vertically (mine is very 'normal'). \$\endgroup\$ Nov 29, 2016 at 13:30
  • \$\begingroup\$ @Tealpelican I didn't come up with this until working out the Fission answer. Before that my best ><> solution was 42 bytes: !__|"druong">o<"figure" (where _ are spaces, and the remaining spaces simply go at the end of the line). \$\endgroup\$ Nov 29, 2016 at 13:32
  • \$\begingroup\$ My shortest current version is this;## " de nr uu og ri GF" > o! ~ ~! < ## Which funny enough is 42 bytes also! My previous versions had error checking but could only reduce to 53 bytes. \$\endgroup\$ Nov 29, 2016 at 14:03
2
\$\begingroup\$

Fission, 37 bytes

Using · to represent spaces.

Figure

D·
"···
f··
i··
g·
u·
r·
e·ound
"·
;·

Try it online!

Ground

·D
·"fi
·gu
·re
·o
·u
·n
·d····
·"
·;

Try it online!

Explanation

Works basically the same as my ><> answer (although I actually found this one first). The only differences are that " prints the characters immediately in Fission, which is why the words aren't written upside down and why we only need to terminate the program with ; at the end.

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

Brian & Chuck, 55 53 bytes

Figure

erugif?dnuorg             
}<.<.<.<.<.<.             

There are 13 trailing spaces on each line.

Try it online!

Ground

             erugif?dnuorg
             }<.<.<.<.<.<.

Try it online!

Explanation

Ah, it's been a while since the last time I used Brian & Chuck. As a short reminder, Brian and Chuck are two Brainfuck-like instances, which use each others' source code as their tape. Only Chuck can use the printing command ., ? switches between the two instances conditionally, and } is sort of like [>] in Brainfuck. Unknown commands are simply ignored.

Since the spaces at the beginning of the programs are ignored, the two programs are almost identical. The only difference comes from the fact that after the switching command ?, the instruction pointer moves before executing the next command. Hence, the first command on Chuck's tape is always skipped. So the only real difference is that the ground program executes the } whereas the figure program doesn't. So here is how the code works:

?   Switch control to Chuck.
}   GROUND PROGRAM ONLY: Move the tape head on Brian to the end of the tape.
<.  Move the tape head left and print the character there.
... Do the same another five times to print the remainder of the string.
\$\endgroup\$
1
\$\begingroup\$

reticular, 46 bytes

                      "ground""figure"" "?$$o;

Try it online! This prints ground.

"ground""figure"""?$$o                 ;      

Try it online! This prints figure.

ground

Relevant code:

"ground""figure"" "?$$o;
................          push these two strings
                " "?$     pop " " off (since " " is truthy, `?` executes `$`)
                     $    pop TOS ("figure")
                      o;  output and terminate

figure

Relevant code:

"ground""figure"""?$$o;
................         push these two strings
                ""?$     doesn't activate
                    $    pop ""
                     o;  output and terminate
\$\endgroup\$
0
\$\begingroup\$

WinDbg, 74 bytes

Ground

                      ea2000000"      groundfigure";;;da       2000006  L6

Figure

ea2000000"groundfigure          ";;;da                  2000006       L6  

Figure has 2 trailing spaces. I feel like at least 2 or 4 bytes ought to be golfable...

It works by writing a string to memory and showing 6 chars from it. The chars in the string are re-arranged so the shown chars change between the programs:

* Ground:
ea 2000000 "      groundfigure";     * Write string "      groundfigure" starting at 2000000
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, from 2000006, ie- ground

* Figure:
ea 2000000 "groundfigure          "; * Write string "groundfigure          " to memory
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, ie- figure

Output:

0:000>                       ea2000000"      groundfigure";;;da       2000006  L6
02000006  "ground"
0:000> ea2000000"groundfigure          ";;;da                  2000006       L6  
02000006  "figure"
\$\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.