165
\$\begingroup\$

Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.
"The twist?" you may ask. Well let me explain:

Your program has to do the following:

  • Be compilable/runnable in two different languages. Different versions of the same language don't count.
  • When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).
  • This is , so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

"trick"

"Treat"

"    TReAt"

"
     tRICk          "

Invalid outputs:

"tri ck"

"tr
eat"

"trck"

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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=97472,OVERRIDE_USER=23417;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=o.replace(TAGS_REG,"")),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,TAGS_REG = /(<([^>]+)>)/ig;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;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\$
13
  • 21
    \$\begingroup\$ This meta answer states that near-duplicates can be tolerated if there's a good reason. I believe that the popularity this question receives from being close to Halloween is a good reason in itself, so I'll vote to reopen. I wouldn't mind closing it after Halloween (but I don't know if this would be a good thing either). \$\endgroup\$
    – Aaron
    Oct 26, 2016 at 14:57
  • 2
    \$\begingroup\$ @mbomb007. This is a duplicate of what? \$\endgroup\$
    – TRiG
    Oct 27, 2016 at 15:03
  • 3
    \$\begingroup\$ definitely not a duplicate. The only thing the same about that other one is that it's also a polyglot challenge with specified output. \$\endgroup\$ Oct 28, 2016 at 14:51
  • 3
    \$\begingroup\$ ... 3 pages... I really think that this is getting a lot of activity based on the current value of the seasonal variant. \$\endgroup\$
    – wizzwizz4
    Oct 29, 2016 at 10:09
  • 2
    \$\begingroup\$ What a great question! I love how some of the answers illuminate and exploit how simple code fragments mean different things in different languages-- e.g. truthiness/falsiness and associativity of the ternary operator. \$\endgroup\$
    – Don Hatch
    Nov 3, 2016 at 22:28

128 Answers 128

3
\$\begingroup\$

HTML/Foo, 19 15 12 bytes

trick<"treat

Displays trick in HTML and prints treat in Foo.

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

Bash / Batch, 37 32 bytes

The perfect contrast, Linux vs. Windows!

echo;echo trick;exit<0echo treat

How it works on Linux: Try it online!

echo;                               -echo nothing
     echo trick;exit;               -echo trick
                     <0echo treat   -ignored by parser (already exited)

How it works on Windows:

echo;                               -echo nothing
                    <0              -find directory (with argument of 0)                  
     echo trick;exit                -can't find directory (skips command)
                      echo treat    -echo treat

-1 byte, Thanks to CartManager XD

-4 bytes by golfing a better way to comment

\$\endgroup\$
5
  • \$\begingroup\$ Why do you need the comment # if you have exited? I don't know batch but I would think echo;echo trick;exit;>NUL&echo treat would work \$\endgroup\$
    – Wheat Wizard
    Apr 23, 2017 at 5:05
  • \$\begingroup\$ Or even echo;echo trick;#>NUL&echo treat. \$\endgroup\$
    – Wheat Wizard
    Apr 23, 2017 at 5:09
  • \$\begingroup\$ @CartManagerXD, that's a good idea, but for some reason the space in between exit and # has to be there. Although, you're right, you can remove the #, and then replace the space with a ;. All in all it removes one byte \$\endgroup\$
    – Graviton
    Apr 23, 2017 at 22:54
  • \$\begingroup\$ What is the purpose of the first echo? \$\endgroup\$
    – user41805
    Aug 10, 2017 at 19:19
  • \$\begingroup\$ @Cowsquack Without it, windows will also echo trick. For some reason echoing something before the echo tick renders everything up to the <0 unparsable for windows. \$\endgroup\$
    – Graviton
    Aug 11, 2017 at 1:35
3
\$\begingroup\$

C/C++, 75 bytes

#include <stdio.h>
int main(){puts(sizeof'a'<sizeof(int)?"treat":"trick");}
\$\endgroup\$
4
  • \$\begingroup\$ Welcome to PPCG! I've added in the byte count for your submission. There are a few optimizations you can make here. For starters, a lot of whitespace is unnecessary, so removing it would shorten the byte count. sizeof('a')<sizeof(int) is shorter by 1, though it causes the outputs to be swapped. Additionally, return types aren't strictly necessary for main - GCC assumes int if it's not explicitly stated. \$\endgroup\$
    – user45941
    Apr 24, 2017 at 5:01
  • \$\begingroup\$ Combining all of my suggestions, this comes out to 74 bytes. \$\endgroup\$
    – user45941
    Apr 24, 2017 at 6:32
  • \$\begingroup\$ Also the parenthesis around the comparison are unnecessary. Which would save another 2 bytes. \$\endgroup\$
    – BrainStone
    Apr 24, 2017 at 9:19
  • \$\begingroup\$ You can remove the space between #include and <stdio.h> to save a byte \$\endgroup\$
    – Maya
    Jan 19, 2018 at 15:01
3
\$\begingroup\$

Java 8 / Whitespace, 169 145 142 141 125 bytes

The Ns are only added so the code has the correct indentations, which represent newlines for the Whitespace part of the program (see explanation below for the spaces and tabs used).

interface M{static void main(String[]a){System.out.print("TREAT");}}N
           N
         N
            N
        N
N
  N
                N
        N
  N
 N
N

Try it here : Whitespace (outputs TRICK)
Try it here : Java 8 (outputs TREAT)

Explanation:

Java:
The Java part is pretty straight-forward. It's a full program with mandatory main-method, which prints TREAT to STDOUT. All (leading and) trailing spaces, tabs and newlines are ignored.

Whitespace:
Whitespace uses spaces, tabs and new-lines as its source-code, ignoring everything else. Here is the same code with the spaces replaced with S, tabs replaced with T, and new-lines appended with N for better readability:

SSSN                          # Push 0    (K)
SSTTSSSN                      # Push -8   (C)
SSTTSSN                       # Push -2   (I)
SSSTTTN                       # Push 7    (R)
SSSTSSTN                      # Push 9    (T)
NSSN                          # Create Label LOOP
 SSSTSSTSTTN                  #  Push 75
 TSSS                         #  Add the top two values on the stack together
 TNSS                         #  Pop and output as character with this codepoint
 NSNN                         #  Jump to Label LOOP

Instead of printing directly, pushing the lowered values in reverse to the stack, and then adding a constant in a loop before printing saves 16 bytes. I've used this approach in a lot of other Whitespace programs of mine, and it can also be found in this Whitespace tip. The constant 75 is generated by this Java program, which I've created for previous challenges.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You should be able to work the java code in. Would save some bytes \$\endgroup\$
    – BrainStone
    Oct 26, 2016 at 8:22
  • \$\begingroup\$ @BrainStone Good point, I've changed it for -24 bytes. Thanks. \$\endgroup\$ Oct 26, 2016 at 8:37
3
\$\begingroup\$

Whitespace / Lost, 112 bytes

v<<<<<<<<<<<>> > > >    >>>>>>
>%?"TRICv+"-+@> > > >        >
                 ^
        ^
    ^
^
  ^
                ^
        ^
  ^
 ^
^
^

Try it online in Lost : TRICK or verify that it's deterministic.
Try it online in Whitespace : TREAT.

Explanation for Lost

Explanation of the language in general:

Lost is a 2D path-walking language. Most 2D path-walking languages start at the top-left position and travel towards the right by default. Lost is unique however, in that both the start position AND starting direction it travels in is completely random. So making the program deterministic, meaning it will have the same output regardless of where it starts or travels, can be quite tricky.

A Lost program of 2 rows and 5 characters per row can have 40 possible program flows. It can start on any one of the 10 characters in the program, and it can start traveling up/north, down/south, left/west, or right/east.

In Lost you therefore want to lead everything to a starting position, so it'll follow the designed path you want it to. In addition, you'll usually have to clean the stack when it starts somewhere in the middle.

Explanation of the program:

Let's ignore everything except for the first two lines. The other lines all point upward/north, to lead the flow towards the following part of the code. (NOTE: The small t are actually tabs (\t). But due to alignment it's better readable like this.)

v<<<<<<<<<<<>> > > >t>>>>>>
>%?"TRICv+"-+@> > >t>t  t >

All the arrows lead towards the leading > of the second line. A minor thing to note about the arrows:

v<<<<<<<<<<<>> > > >t>>>>>>

could also have been:

v<<<<<<<<<<<<< < < <t<<<<<<

Lost programs will wrap around in all directions; i.e. when it goes out of bounds at the left-hand side traveling in a west/left direction, it continues at the right-hand side in that same direction. Because of this, using <<<>>> will have a shorter path and is therefore slightly better for performance than <<<<<<, and since it doesn't affect the byte-count anyway, why not use it. :)

An additional minor note: these alternating trailing parts are there because we need to fit the spaces/tabs of the Whitespace program in it:

 > > >t>>>>>>
> > >t>t  t >

So, all those arrows, including the v after the C in the string (more on that in a moment), will lead to the leading > on the second line. After that, the program flows and execution is as follows:

  • >: travel in an east/right direction
  • %: Put the safety 'off'. In a Lost program, an @ will terminate the program, but only when the safety is 'off'. When the program starts, the safety is always 'on' by default, otherwise a program flow starting at the exit character @ would immediately terminate without doing anything. The % will turn this safety 'off', so when we now encounter an @ the program will terminate (if the safety is still 'on', the @ will be a no-op instead).
  • ?: Clean the top value on the stack. In some program flows it's highly likely we have a partial string on the stack, so we use this to wipe the stack clean of that potential string.
  • ": Start a string, which means it will push the integer code-points of the characters used (rather similar as the Whitespace program).
  • TRICv+: Push the code-points for these characters, being 84 82 73 67 118 43 respectively
  • ": We're done pushing code-points of this string
  • -+: Subtract the top two values from each other, so the 118 43 becomes 75 (K). (NOTE: -+ are actually two loose operands: - will negate the top value on the stack (multiply it by -1), and + will add the top two values on the stack together.)
  • @: Terminate the program if the safety is 'off' (which it is at this point). After which all the values on the stack will be output implicitly. Using the -A program argument flag these code-points will be output as characters instead.

Explanation for Whitespace:

Explanation of the language in general:

Whitespace is a stack-based language using only spaces ( ), tabs (\t), and newlines (\n) (hereafter indicated with STN respectively). Any other character is ignored. Printing in Whitespace can either be done as character or as integer. When it outputs as character, it will use an integer on the stack as code-point and convert it to its corresponding UTF-8 character before outputting.

Integers are pushed to the stack as follows:

  • S: Enable Stack Manipulation
  • S: Push what follows as integer to the stack
  • S/T: Sign bit where S is positive and T is negative
  • Some T and S followed by an N: Put number as binary to the stack (T=1 and S=0)

For example: SSSTSTSN will push 10 to the stack.

Explanation of the program:

If we ignore all non-whitespace characters, the program will be this:

SSSTN           # Push 1     (T)
SSTTSSTSN       # Push -18   (A)
SSTTTTSN        # Push -14   (E)
SSTTN           # Push -1    (R)
SSSTN           # Push 1     (T)
NSSN            # Create Label LOOP
  SSSTSTSSTTN   #   Push 83
  TSSS          #   Add top two values on the stack together
  TNSS          #   Pop and output top of the stack as character with this code-point
  NSNN          #   Jump to Label LOOP

Instead of directly pushing and printing each character, I push all characters to the stack in reversed order, with each of their code-points lowered by a constant value. In a loop I then add this constant to the integer, before popping and outputting it as character. See this Whitespace tip of mine for more information on this approach.
The constant 83 is the most efficient constant for this output-text, which is generated by this Java program, a generator I've created and used for some of my other Whitespace answers in the past.

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

Ruby / Brat, 26 bytes

#*
puts:treat
$*#p :trick

Ruby prints treat and Brat prints trick.

Ruby

The first line is a comment starting with #, so ignored. The second line prints out treat (the parser is liberal enough we don't need a space).

The last line is interpreted as $* (a global variable) and the rest is ignored as a comment starting with #.

Brat

In Brat, #* begins a multi-line comment and *# ends it.

The first line begins a multi-line comment, so the second line is ignored.

Brat sees $ as part of the comment and *# closes the comment started above. That leaves p :treat to print out treat.

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

QBIC and QBasic 4.5, 45 bytes

QBIC is my attempt at a golfing language, based on QBasic. The language has evolved quite a bit from its original, as I think this snippet illustrates:

A$=STR$(q):IF A$=" 1"THEN?"trick"ELSE?"treat"

The space before the 1 is significant. QBIC will print trick, QBasic will show treat. So, what's going on here. First, QBasic:

A$=STR$(q)          Set A$ to a string representation of the number q                        
IF A$=" 1"          A$ is now " 0" because 'q' is not set and 0 by default.
                    Space added by STR$ :'(  
THEN PRINT "trick"  Ignored
ELSE PRINT "treat"  Printed

Now QBIC. This one is a little more complex:

A                   Creates A$ in te output BAS
$                   Start a Code Literal. QBIC is not yet very function-complete,
                    so on occasion we need to call QBASIC functions directly. However,
                    that may interfere with QBIC syntax. When a '$' is encountered,
                    QBIC ignores everything from that $ until a '|' or EOF and
                    just passes this along as QBASIC.  
=STR$(q)            Set A$ to a string representation of the number q                        
IF A$=" 1"          A$ is now " 1" because 'q' is pre-initilised to 1 by QBIC                       
THEN PRINT "trick"  printed
ELSE PRINT "treat"  ignored

We don't need END-IFs, because in the snippet the IF is in-line.

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

Dart - JavaScript (68 bytes)

Seems appropriate as Google has been livestreaming the Dart Developer Summit for the past two days.

var a=main();function main(){1==true?alert("Treat"):print("Trick");}

Formatted:

var a = main();

function main() {
  1 == true ? alert("Treat") : print("Trick");
}

main method

In Dart static variables may only be initialized with compile-time constants (hereafter referred to as just constants in the interest of brevity). Static variables include all top-level variables as well as static variables of classes.

^ http://news.dartlang.org/2012/02/static-variables-no-longer-have-to-be.html

The Dart VM starts by immediately calling the main method. As the variable 'a' is a top level one, the Dart VM will only initialize it when it's needed (lazy initialization).

JavaScript immediately initializes the variable by which the main method also gets invoked.


truthy/falsey

Dart differs from JavaScript in its treatment of truthy and falsey values. In JavaScript, the objects 1, non-empty string, and non-null objects are treated as true. In Dart, it’s more simple. Only the boolean value true is treated as true. In Dart, all object instances other than true are treated as false.

^ https://www.dartlang.org/resources/dart-tips/dart-tips-ep-4

The above quote explains why 1 == true evaluates to true in JavaScript whilst it gets evaluated to false in Dart.

\$\endgroup\$
3
  • \$\begingroup\$ Couldn't you just use 1? instead? And at least in JavaScript you can get rid of the outer most parentheses. I don't know about dart though \$\endgroup\$
    – BrainStone
    Oct 27, 2016 at 18:37
  • \$\begingroup\$ @BrainStone nope. As Dart requires a static type of bool for conditions, you can't just use integer ? : \$\endgroup\$ Oct 27, 2016 at 19:11
  • \$\begingroup\$ @BrainStone you're right about the outer most parentheses though! Thanks for the heads up \$\endgroup\$ Oct 27, 2016 at 19:12
2
\$\begingroup\$

Python 2 and C, 93 bytes

It's not exactly a competitive entry, but it was certainly a fun challenge. The Python section prints trick while the C portion prints treat.

#include <stdio.h>/*
print'trick'
#*/
#define pass int main(){puts("treat");return 0;}
pass
\$\endgroup\$
2
\$\begingroup\$

C / Shell 57 50 bytes

Should be more verbose to match the C99 (missing include, no return value in main etc). But it runs fine with gcc, clang and tcc:

Updated version:

#define echo main(){puts("trick");}int
echo treat;

Initial version:

#define echo main(){puts("trick");}void*p=
echo "treat";
\$\endgroup\$
4
  • \$\begingroup\$ this could be shortened to #define echo main(){puts("trick");}int and echo treat; \$\endgroup\$ Oct 29, 2016 at 5:17
  • \$\begingroup\$ @technosaurus Might work in some compilers, but gcc throws an error - not a constant initializer. \$\endgroup\$
    – zserge
    Oct 29, 2016 at 11:01
  • \$\begingroup\$ I didn't have an = sign, so it shouldn't complain about an initializer. After preprocessing, C should see echo main(){puts("trick");}int treat;... which is just an unused (and uninitialized) variable named treat ... I think you may have added an equal sign to the end of the #define block. ... which brings it down to 50 bytes. \$\endgroup\$ Oct 29, 2016 at 17:52
  • 1
    \$\begingroup\$ You don't need int in C89; a bare treat; will default to int. \$\endgroup\$
    – Dennis
    Oct 30, 2016 at 4:03
2
\$\begingroup\$

C / JavaScript (75 bytes)

Works with Clang on Mac, with some warnings, and Node.js.

main()
{puts("trick");}//\
function main(){puts=()=>console.log("treat");}

75 bytes is quite a bit but JavaScript is a verbose language for code golf.

I took inspiration from I_LIKE_BREAD7 for the escaped comment line to include non-C code in a .c file.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 64 bytes: //\\nmain=_=>{puts=_=>console.log`treat`}\nmain()\n{puts("trick");} (replace all \n with a REAL newline.) Example in C (ideone.com/YToPEb) and in Javascript (jsfiddle.net/1m2yfdow). \$\endgroup\$ Nov 1, 2016 at 23:44
  • 1
    \$\begingroup\$ I've actually reduced it to 62 bytes: //\\nmain=_=>{puts=_=>console.log`treat`}\nmain()\n{puts("tr‌​ick");}. All I did was replacing main=_=>{puts=_=>console.log`treat`} with main=_=>puts=_=>console.log`treat` . Try it on jsfiddle.net/1m2yfdow/1. This is a Javascript-only change, so, C won't be affected \$\endgroup\$ Nov 2, 2016 at 17:27
2
\$\begingroup\$

Python / JavaScript, 32 bytes

1//2;print"trick"
alert("treat")

Python runs 1//2;, which integer divides 1 by 2, then prints "trick". alert("treat") causes a runtime error because alert is not a function, but I believe this is allowed.

JavaScript runs 1 and sees the rest of the line as a comment. The second line alerts "treat".

Note that I can't shorten alert("treat") to alert`treat` because Python will throw a syntax error during compilation.

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

Python, Lua 31 or 32 bytes

s="trick"
--0;s="treat"
print s

The one above has to be run using python 2.

s="trick"
--0;s="treat"
print(s)

The -- designates a comment in Lua, while it is two negatives in Python. Prints "trick" in Lua, but prints "treat" in Python.

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

Lua, Ruby - 31 bytes

s="trick"
--0;s="treat"
print s

The explanation is the same as my Python/Lua answer. Prints treat in Ruby, trick in Lua.

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

Clojure/Groovy, 37 bytes

;/*
(println"trick");*/println"treat"

Clojure (trick)

The ; denotes a single-line comment, so Clojure sees:

(println "trick")

Groovy (treat)

Any single ; is a valid statement that does nothing. Obviously /* ... */ is a multi-line comment. Groovy sees:

println "treat"
\$\endgroup\$
2
\$\begingroup\$

Python / Japt, 22 bytes

1
print"trick";"treat"

Python

This should be fairly obvious: print"trick" prints trick; 1 and "treat" don't do anything.

Japt

This code transpiles to

1
.p("r".i("n".t(("trick"))));("treat")

The result of last expression is automatically sent to STDOUT, so this prints treat.

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

Cubix / Japt, 24 bytes

WHAT"kcirt"u@!C;Co} `É.t

Test Cubix | Test Japt

The . represents the unprintable char U+0084.

Japt

Before running Japt code, it is first transpiled to JavaScript. The various features transpile roughly to:

WHAT    "kcirt"u  @               !C;       Co      `É.t
W,H,A,T,"kcirt".u(function(X,Y,Z){!C;return C.o()}),"treat"

The the code is evaluated, and the result of the last expression is sent to STDOUT. W,H,A,T are variables, but they're effectively no-ops since we don't do anything with them. "kcirt".u() makes the string uppercase, ignoring the function, but again, this is discarded. The only thing that matters is the "treat" at the end; this is printed, end then the program ends.

Cubix

Before the code is run, all whitespace is removed, and the code is transformed into the smallest cube net possible, padded with . no-ops. This particular program becomes:

    W H
    A T
" k c i r t " u
@ ! C ; C o } `
    É .
    t .

Then the code is run like a regular 2D language, with the IP (instruction pointer) starting at the top-left corner of the leftmost face. Here's what happens:

  • "kcirt" - Push the char codes of these letters to the stack.
  • u - Make a U-turn to the right, going down a row in the process.
  • ` - Not implemented, so a no-op.
  • } - Another no-op.
  • o - Output the char-code on top of the stack (t).
  • C - Another no-op.
  • ; - Remove the top item.
  • C - Another no-op.
  • ! - If the top item is non-zero, skip the next instruction (@).

Since the top item is non-zero, the IP jumps the @ and wraps back around to the `. This repeats until the last character has been outputted, at which point ! fails and the IP hits @, ending the program.


Old solution, 25 bytes

"treat"//"kcirt"under@!;o

Test Cubix | Test Japt

Japt

This is very simple: // and everything after is a comment, so the only thing evaluated is "treat". This is implicitly printed to STDOUT.

Cubix

The code is expanded to the following cube net:

      " t r
      e a t
      " / /
" k c i r t " u n d e r
@ ! ; o . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

Then the code is run like a regular 2D language, with the IP (instruction pointer) starting at the top-left corner of the leftmost face. Here's what happens:

  • "kcirt" - Push the char codes of these letters to the stack.
  • u - Make a U-turn to the right, going down a row in the process.
  • .... - A bunch of no-ops.
  • o - Output the char-code on top of the stack (t).
  • ; - Remove the top item.
  • ! - If the top item is non-zero, skip the next instruction.

The IP then wraps around to the right, so these last 3 instructions repeat until the stack is empty. Then ! fails, so the IP lands on @, which ends the program. The Japt code is conveniently contained on the top face and never gets run.

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

C / Octave, 63 bytes

#define f() main(){puts("trick");}//\
f=@()(disp("treat"));
f()

Explanation:

What C sees:

#define f() main(){ puts("trick"); } //comment
f()

What Octave sees:

#comment
f = @()(disp("treat"));
f()

Pretty straightforward.

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

Excel / Google Sheets, 28 Bytes

Anonymous worksheet formula that takes no input and outputs "Trick" to the calling cell in Excel and "Treat" to the calling cell in Google Sheets

=IfError(M("Treat"),"Trick")
\$\endgroup\$
2
\$\begingroup\$

Javascript/Ruby, 35 30 bytes

0?puts("trick"):alert("treat")

0 is truthy in Ruby, but not in Javascript.

Edit: Saved 5 bytes by replacing []==[] with 0.

\$\endgroup\$
1
  • \$\begingroup\$ As far as I know, JS doesn't compare by value. It compares if it's the same object, which it is not, as you are initializing two different empty arrays. \$\endgroup\$
    – BrainStone
    Jan 17, 2018 at 17:15
2
\$\begingroup\$

Runic Enchantments (treat) & Gol><> (trick), 15 bytes

"kcirt"H>'ອE@

Try it online! (Runic)

Try it online! (Gol><>)

The Gol><> is pretty straight forward. It pushes the char-literals for "trick" in reverse order, then H causes the entire stack to be dumped to output before terminating.

Runic starts at the >, pushes the char-literal (decimal value 3757) and calls E which causes a dictionary lookup on 3757, which is "treat", @ dumps stack and terminates.

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

Forth (gforth) / Python 3, 32 bytes

0. # ." trick"
( print("treat"))

Try it online: (gforth, python)

Explanation

Not the most clever approach, effectively uses the different comment styles to have each language run its own code.

# starts a line comment in python, but adds the lowest digit of a double-length number to an output string in forth. 0. is used as the double-length number in forth, but unused in python

Standalone parentheses are used for grouping in python (and are ignored when unneeded), while they denote a block comment in forth.

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

Haskell and ink, 31 or 42 29 bytes

trick/*b=b
main=putStr"treat"

Try it online! (Haskell, ink)

Explained

Ink doesn't mind unclosed multiline comments, so as far as ink is concerned, the program is just trick, which gets printed literally.

Haskell interprets the first line as defining a function /* that takes two parameters named trick and b and returning the latter. main just prints "treat"

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

Keg / Foo, 14 bytes

("Treat")Trick

Try it online!

Try It online!

Explanation

Foo

("Treat")      Push "Treat"
         Trick NOPS
               Implicit print

Keg

("Treat")      # For loop over stack length. Stack is empty, therefore it is skipped.
         Trick # Push "Trick"
               # Implicit print
\$\endgroup\$
1
\$\begingroup\$

Clojure/Script

Clojure

(prn (if (= (str (type "")) "class java.lang.String") "trick" "treat"))

ClojureScript

(prn (if (= (str (type "")) "class java.lang.String") "trick" "treat"))

Explanation

Clojure compiles down to JavaScript, and works quite the same as it does in Java.

"class java.lang.String" is not available in JavaScript, but, the if statements and prn work exactly the main.

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

Dart, Dart2JS, 49 bytes

main(){print(identical(1,1.0)?"Treat":"Trick");}

running by dart gives:

$ dart web/test.dart 
Trick

for compiled version:

$ dart2js web/test.dart
$ nodejs out.js
Treat
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Hello, and welcome to PPCG! This question is code-golf, so please include the number of bytes in your code, and the two languages (dart2js, dart) that you use. Also, please remove extra spaces in your code. \$\endgroup\$ Oct 27, 2016 at 18:21
1
\$\begingroup\$

/// / ><>, 22 bytes

\treat/
>"kcirt"ooooo;

Try it online! Slashes | Fish

Explanation

(♥ is a newline)

  • ///

    \t                      Print "t"
      reat                  Print "reat"
          /♥>"kcirt"ooooo;  Incomplete replacement, ignored
    
  • ><>

    \                       Mirror, makes IP go down
           ♥>               Go right
             "kcirt"ooooo   Print "trick"
                         ;  End program
    
\$\endgroup\$
1
\$\begingroup\$

CJam/Befunge, 21 bytes

"Trick"o"taerT",,,,,@

Try it online! (CJam)
Try it online! (Befunge)


CJam:

"Trick"o push "Trick" and print it.
"taerT", push "taerT" and take length, 5.
,,,, take lengths of ranges, leaves 5.
@ tries to rotate top three elements.

CJam would normally print the stack on exit, but with only a single element the rotation causes an empty stack exception and the 5 is left unprinted.

Befunge:

"Trick" push each letter of "Trick".
o is unspecified and gets ignored.
"taerT" push each letter of "Treat" in reverse.
,,,,, pop and print 5 letters ("Treat")
@ terminates Befunge naturally.

Befunge doesn't print the stack on exit so the letters from "Trick" don't cause a problem. However, the unspecified o may be treated differently on other interpreters. For instance this one would reverse the instruction pointer and wrap back to @ with no output.

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

Scheme / Brainf*ck, 80 bytes

My second attempt.

(print 'trick);++++[>+++++[>+++++<-]<-]>>[>+>+<<-]++++[>++++<-]>.--.>+.----.<++.

What Scheme sees: (print 'trick)

What Brainf*ck sees: ++++[>+++++[>+++++<-]<-]>>[>+>+<<-]++++[>++++<-]>.--.>+.----.<++.

Happy Halloween.

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

JavaScript (with SpiderMonkey print)/Python - 32 bytes

a=1
print(["trick","treat"][--a])
\$\endgroup\$
2
  • \$\begingroup\$ Would a=1;print(["trick","treat"][--a]) work instead? \$\endgroup\$ Nov 3, 2016 at 20:48
  • \$\begingroup\$ Yes, that works! \$\endgroup\$
    – Adalynn
    Nov 3, 2016 at 21:07

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.