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
    Commented Oct 26, 2016 at 14:57
  • 2
    \$\begingroup\$ @mbomb007. This is a duplicate of what? \$\endgroup\$
    – TRiG
    Commented 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\$ Commented 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
    Commented 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
    Commented Nov 3, 2016 at 22:28

128 Answers 128

1
2 3 4 5
207
\$\begingroup\$

Python / Windows Batch, 25 bytes

print"trick"#||echo.treat

Everything after the # is interpreted as a comment by python, while the || is an OR in batch, saying that as the previous command failed, execute this one.

I also like the use of an OR as it almost reads "trick or treat" :)

\$\endgroup\$
12
  • 36
    \$\begingroup\$ TBH I up-voted this just for the comment about the OR. \$\endgroup\$
    – Jmons
    Commented Oct 26, 2016 at 10:07
  • 8
    \$\begingroup\$ TBH I never ever expected my first post here to get 65 upvotes :) \$\endgroup\$
    – cure
    Commented Oct 27, 2016 at 15:54
  • 12
    \$\begingroup\$ TBH lets not just talk about upvotes. Its not Quora \$\endgroup\$
    – S Andrew
    Commented Oct 28, 2016 at 10:13
  • 3
    \$\begingroup\$ @SAndrew as a brand new member of this community, i didnt expect to make a post that would be this well recieved this soon, and i'm happy to have been able to contribute. I'm not trying to brag, please don't misunderstand. I'm just really happy to be so well recieved as i'm so new. thanks for you're comment :) \$\endgroup\$
    – cure
    Commented Oct 29, 2016 at 15:39
  • 2
    \$\begingroup\$ @nephi12 I have tried running your code, but it doesn't seem to work. Running it on Python, as expected, runs flawlessly. But in a bat file, it just writes 'print"trick"#' is not recognized as an internal or external command, operable program or batch file. However, this version has worked for me: print "trick"#|echo.treat - piping the output to the echo \$\endgroup\$ Commented Oct 29, 2016 at 15:43
160
\$\begingroup\$

Whitespace / Starry, 135 bytes

Here's to a clear night sky on Halloween!


  + +    +      + + 
    +

* +   +*      +     *

   +    *           
     + +        

 +* +   



 +* + .  + .   +      +* +   +* . . .

Note that whitespace on empty lines may not be preserved if you copy from the above code

Whitespace outputs "TRICK". Try it Online!
Starry outputs "TREAT". Try it Online!

Explanation

Starry

Starry ignores all tabs and new lines so the code it reads is the following

         + + + + + +  * +   +*   +  *   +  *       + +   +* +   +* + .  + .   +      +* +   +* . . .

Bytewise, pushing values is very expensive compared to stack and arithmetic operations in Starry. The code starts by pushing and duplicating 4 and the performs a number of operations on it and with 2 and 1 pushed later on produces all of the required ASCII values.

Annotated Code

Stack (after op)    Code        Operation
4                            +  Push 4
4 4 4 4 4 4          + + + + +  Duplicate top of stack 5 times
4 4 4 4 16            *         Multiply top two items
4 4 4 4 16 16        +          Duplicate top of stack
4 4 4 16 4 16          +        Rotate top three items on stack right
4 4 4 16 20         *           Add top two items
4 4 20 4 16            +        Rotate...
4 4 20 64             *         Multiply...
4 64 4 20              +        Rotate...
4 64 80               *         Multiply...
4 64 80 2                  +    Push 2
4 64 80 2 2          +          Duplicate...
4 64 2 80 2            +        Rotate...
4 64 2 82           *           Add...
4 64 2 82 82         +          Duplicate...
4 64 82 2 82           +        Rotate...
4 64 82 84          *           Add...
4 64 82 84 84          +        Rotate...
4 64 82 84           .          Pop and print as character (T)
4 64 84 82            +         Swap top two items on stack
4 64 84              .          Pop and print... (R)
84 4 64                +        Rotate...
84 4 64 1                 +     Push 1
84 4 65             *           Add...
84 4 65 65           +          Duplicate...
84 65 4 65             +        Rotate...
84 65 69            *           Add...
84 65                .          Pop and print... (E)
84                   .          Pop and print... (A)
                     .          Pop and print... (T)

Whitespace

As the name may suggest, Whitespace only parses the three whitespace characters—space, tab, and newline. Unlike the Starry, the Whitespace simply pushes the ASCII values of T, R, I, C, and K and the prints them.

Annotated Code

<Space><Space><Space><Tab><Space><Tab><Space><Space><Tab><Space><LF> Push the ASCII value of R
<Space><Space><Space><Tab><Space><Tab><Space><Tab><Space><Space><LF> Push the ASCII value of T
<Tab><LF><Space><Space> Pop and print the T
<Tab><LF><Space><Space> Pop and print the R
<Space><Space><Space><Tab><Space><Space><Tab><Space><Space><Tab><LF> Push the ASCII value of I
<Tab><LF><Space><Space> Pop and print the I
<Space><Space><Space><Tab><Space><Space><Tab><Space><Tab><Tab><LF>   Push the ASCII value of K
<Space><Space><Space><Tab><Space><Space><Space><Space><Tab><Tab><LF> Push the ASCII value of C
<Tab><LF><Space><Space> Pop and print the C
<Tab><LF><Space><Space> Pop and print the K
<LF><LF><LF>            Terminate the program. The following line is not run.
<Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><LF>

The interweaving of pushes and prints was chosen based solely on aesthetic reasons as it does not affect the byte count.

\$\endgroup\$
2
  • 13
    \$\begingroup\$ so beautiful sky \$\endgroup\$
    – lois6b
    Commented Oct 26, 2016 at 7:14
  • 9
    \$\begingroup\$ this is by far the best answer, so creative. im shocked by the ingenuity. and the skill. bravo! \$\endgroup\$
    – cure
    Commented Oct 27, 2016 at 5:16
154
+250
\$\begingroup\$

2sable / pl, 8 bytes

0000000: 74 72 65 61 74 93 d0 cb                          treat...

Both programs have been tested locally with the same 8 byte file, so this is a proper polyglot.

2sable: trick

This is the program in code page 1252.

treat“ÐË

Try it online!

pl: treat

This is the program in code page 437.

treatô╨╦

Try it online!

How it works

2sable: trick

t         Square root. Errors since there is no input. The exception is caught, the
          stack left unaltered, and the interpreter pretends nothing happened.
 r        Reverse stack.
          Reversed empty stack is still empty stack. ;(
  e       Compute nCr. Errors since there is no input.
   a      Alphanumeric test. Errors since there is no input.
    t     Square root. Errors since there is no input.
     “    Begin a lowercase string literal.
      Ð     Excluding ‘, ’, “, and ”, Ð is the 71st non-ASCII character in CP1252.
       Ë    Excluding ‘, ’, “, and ”, Ë is the 66th non-ASCII character in CP1252.
          (implicit) End string literal.
          Both characters together fetch the dictionary word at index
          71 * 100 + 66 = 7166, which is 'trick'.

pl: treat

treat     Bareword; push the string "treat" on the stack.
     ô    Unimplemented. Does nothing.
      ╨   Flatten the stack. This doesn't affect the output.
       ╦  Unimplemented. Does nothing.
\$\endgroup\$
4
  • 18
    \$\begingroup\$ But I've got to admit this answer is plain ridiculous! What's next? An answer that's shorter than the words themself? \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 19:50
  • 47
    \$\begingroup\$ This answer is extremely impressive. It's amazing that you managed to write a program shorter than the length of the two words. \$\endgroup\$
    – DJMcMayhem
    Commented Oct 26, 2016 at 21:20
  • 1
    \$\begingroup\$ Huh? Those are 2 programs \$\endgroup\$
    – kepe
    Commented Oct 25, 2018 at 18:19
  • 4
    \$\begingroup\$ @FireCubez It's the same code, byte per byte. The visual representation varies with the codepage though. \$\endgroup\$
    – Dennis
    Commented Oct 25, 2018 at 18:27
141
\$\begingroup\$

Linux ELF x86 / DOS .COM file, 73 bytes

00000000  7f 45 4c 46 01 00 00 00  1a 00 00 00 1a 00 43 05  |.ELF..........C.|
00000010  02 00 03 00 1a 00 43 05  1a 00 43 05 04 00 00 00  |......C...C.....|
00000020  eb 0c b4 09 ba 41 01 cd  21 c3 20 00 01 00 b2 05  |.....A..!. .....|
00000030  b9 3b 00 43 05 cd 80 2c  04 cd 80 74 72 69 63 6b  |.;.C...,...trick|
00000040  00 74 72 65 61 74 24 eb  d9                       |.treat$..|
00000049

NASM source:

ORG 0x05430000

BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class 32b   | -- | type: PT_LOAD      |
                                                ; |*data none   |    |                    |
                                                ; |*version 0   |    |                    |
                                                ; |*ABI SysV    |    |                    |
DD 0x01a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  DD 0x0543001a                           ; |*PADx7       | -- | vaddr = 0x0543001a |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x0543001a                                   ; |*version     | -- | filesz             |
;       inc     ebx     ; STDOUT_FILENO         ; |             |    |                    |
;       mov     eax, 4  ; SYS_WRITE             ; |             |    |                    |
DD 0x0543001a                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
        jmp     short skip                      ; |*sh offset   | -- |*align              |
BITS 16                                         ; |             |    |                    |
treat:  mov     ah, 9                           ; |             | -- |                    |
        mov     dx, trick + 0x100 + 6           ; |*flags ______|    |                    |
        int     0x21                            ; |______/      |    +--------------------+
        ret                                     ; |*ehsize      |
BITS 32                                         ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
skip:                                           ; |             |
        mov     dl, 5   ; strlen("trick")       ; |*shentsize   |
        mov     ecx, trick                      ; |*shnum       |
                                                ; |*shstrndx    |
                                                ; +-------------+
        int     0x80
        sub     al, 4   ; SYS_EXIT
        int     0x80


trick:  DB      "trick/treat$"

BITS 16
        jmp     short treat

This uses the fact that the ELF header starts with 7F 45, which, interpreted as x86 code, is a jump.

The relevant parts for the DOS .COM:

-u100 l2
07D2:0100 7F45          JG      0147
-u147 l2
07D2:0147 EBD9          JMP     0122
-u122 l8
07D2:0122 B409          MOV     AH,09
07D2:0124 BA4101        MOV     DX,0141
07D2:0127 CD21          INT     21
07D2:0129 C3            RET
-d141 l6
07D2:0140     74 72 65 61 74 24   -                           treat$
\$\endgroup\$
5
  • 4
    \$\begingroup\$ Bravo, sir. Bravo. \$\endgroup\$
    – Draconis
    Commented Oct 26, 2016 at 22:37
  • 10
    \$\begingroup\$ My heart skipped a beat. \$\endgroup\$ Commented Oct 27, 2016 at 13:59
  • \$\begingroup\$ muppetlabs.com/~breadbox/software/tiny/teensy.html is a good read for anyone interested in the header overlap trick here. \$\endgroup\$
    – Sparr
    Commented Oct 31, 2016 at 16:26
  • 4
    \$\begingroup\$ This is one of the finest answers i've ever seen on this site. Codegolf a little too often turns into esoteric languages purpose-built for golfing, rather than clever answers. This is beautiful. \$\endgroup\$
    – Knetic
    Commented Nov 1, 2016 at 20:46
  • \$\begingroup\$ This is great stuff. \$\endgroup\$
    – Gooseman
    Commented Jan 18, 2017 at 12:08
105
\$\begingroup\$

evil / ZOMBIE, 109 bytes

Another spooky answer !

xf is a vampire summon task f say "trick" stumble say "jzuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw" animate bind

The ZOMBIE code defines a vampire named xf whose only task f is activated at instanciation and will output trick once before being deactivated by stumble. The other say call is dead code (how appropriate !) for ZOMBIE, but contains most of the evil code.

For evil, the xf name is a call to jump to the next j, which precedes the zuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw zombie moan that crafts and output treat. The code following is either executed (lowercase letters) or ignored but since there's no w no output should be produced.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ @KevinCruijssen thanks, I enjoyed this occasion to get into some less-known esoteric languages :) \$\endgroup\$
    – Aaron
    Commented Oct 26, 2016 at 13:40
  • \$\begingroup\$ Well, from the four you've used I have seen Agony a few times before, and I vaguely remember to have seen ZOMBIE once. Never heard of HashHell or evil before, though. :) \$\endgroup\$ Commented Oct 26, 2016 at 13:43
  • \$\begingroup\$ the Halloween theming of this is impressive! I'd never even heard of those two languages \$\endgroup\$
    – ejfrancis
    Commented Oct 27, 2016 at 21:36
97
\$\begingroup\$

Python / Perl, 28 bytes

print([]and"trick"or"treat")

Explanation

Since [] is an ArrayRef in Perl, it's truthy, but it's an empty array in Python, therefore falsy.

\$\endgroup\$
5
  • 7
    \$\begingroup\$ Similarly, print({}and"trick"or"treat") in Python / Lua. \$\endgroup\$
    – user200783
    Commented Oct 27, 2016 at 4:01
  • 1
    \$\begingroup\$ @user200783 That would have the same effect in Perl as well, since {} is a HashRef! \$\endgroup\$ Commented Oct 27, 2016 at 7:05
  • 2
    \$\begingroup\$ Is also almost identical for Python / Ruby, but requires an extra whitespace: print ([]and"trick"or"treat") \$\endgroup\$
    – Value Ink
    Commented Oct 28, 2016 at 5:21
  • 2
    \$\begingroup\$ Love it! This is a great commentary on what implicit conversion-to-bool does to readability. \$\endgroup\$
    – Don Hatch
    Commented Nov 3, 2016 at 22:21
  • \$\begingroup\$ This could be a polyglot in Lua, Perl, and Python if it were print({}and"trick"or"treat")! \$\endgroup\$
    – ckjbgames
    Commented Apr 23, 2017 at 23:54
47
\$\begingroup\$

PHP / JavaScript, 32 30 bytes

Displays trick in PHP and treat in JS.

NaN?die(trick):alert('treat');

The unknown NaN constant is implicitly converted to a string by PHP, making it truthy. It's falsy in JS.

Alternative method, 38 bytes

(1?0:1?0:1)?die(trick):alert('treat');

The ternary operator is right-associative in JS:

                1 ? 0 : 1 ? 0 : 1
 is parsed as:  1 ? 0 : (1 ? 0 : 1)
 which equals:  0

And left-associative in PHP:

                1 ? 0 : 1 ? 0 : 1
 is parsed as:  (1 ? 0 : 1) ? 0 : 1
 which equals:  1
\$\endgroup\$
5
  • 1
    \$\begingroup\$ You're right, my bad \$\endgroup\$ Commented Oct 27, 2016 at 14:32
  • \$\begingroup\$ alert() is JavaScript in HTML, though, not JavaScript from the console. \$\endgroup\$ Commented Oct 29, 2016 at 19:03
  • 1
    \$\begingroup\$ Alternative method: '\0'=="\0"?die(trick):alert('treat');`. \$\endgroup\$ Commented Oct 30, 2016 at 5:00
  • 3
    \$\begingroup\$ Debugging chained ternary operators in PHP must be so much fun. \$\endgroup\$ Commented Oct 30, 2016 at 9:08
  • 3
    \$\begingroup\$ @Robert Debugging anything in PHP is so much fun. \$\endgroup\$ Commented Nov 3, 2016 at 7:00
39
\$\begingroup\$

HTML / HTML+JavaScript, 53 bytes

treat<script>document.body.innerHTML='trick'</script>

treat is the document´s text content in HTML.
If JS is enabled, it will replace the HTML content with trick.

\$\endgroup\$
5
  • 3
    \$\begingroup\$ Interesting solution. I like it \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 13:19
  • 1
    \$\begingroup\$ You should use document.write() instead. -8 bytes \$\endgroup\$
    – darrylyeo
    Commented Oct 27, 2016 at 14:18
  • \$\begingroup\$ @darrylyeo document.write would not replace the HTML output but append to it. \$\endgroup\$
    – Titus
    Commented Oct 27, 2016 at 14:29
  • 1
    \$\begingroup\$ Tested in Chrome. Fully works. Turning javascript on and off changes the content on refresh. \$\endgroup\$
    – Tatarize
    Commented Oct 30, 2016 at 17:18
  • \$\begingroup\$ @Tatarize: Tested in Firefox 49, Opera 41, Safari 5.0, Chrome 54, Edge 38 on Windows, Firefox 5.3 and Safari 5.0 on iOS, Firefox 49 and Dolphin 11.5 on Android. Only Firefox on Windows replaces; all others append. \$\endgroup\$
    – Titus
    Commented Nov 18, 2016 at 12:22
33
\$\begingroup\$

C / Java 7, 165 155 128 123 122 120 103 bytes

//\
class a{public static void main(String[] s){System.out.print("treat"/*
main(){{puts("trick"/**/);}}

//\ makes the next line also a comment in C but is a regular one line comment in Java, so you can make C ignore code meant for Java and by adding /* in the second line you can make a comment for Java that is parsed as code by C.

Edit: I improved it a little bit by reorganizing the lines and comments.

Edit2: I did some more reorganizing and shortened it even more.

Edit3: I added corrections suggested by BrainStone to remove 5 bytes, thanks :)

Edit4: One newline turned out to be unnecessary so I removed it.

Edit5: I changed printf to puts.

Edit6: I added a correction suggested by Ray Hamel.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You can safe 1 byte by changing C to C++ and replacing #include<stdio.h> with #include<cstdio>. Not much but a byte is a byte. And additionally removing int infront of main will safe 4 bytes. int is implied by C and C++ \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 20:00
  • \$\begingroup\$ Thanks, I modified the code according to your suggestions :) \$\endgroup\$ Commented Oct 27, 2016 at 2:15
  • 1
    \$\begingroup\$ Nice! I had a hard time coming up with something for Java, and ended up with Java 7 + Whitespace myself. Btw, you can golf one more byte by removing the space at String[]s. \$\endgroup\$ Commented Nov 4, 2016 at 13:31
29
\$\begingroup\$

Jolf + Chaîne, 12 bytes

Because Chaîne cannot accept a file to upload with an encoding, I assume UTF-8. (If I could assume ISO-8859-7, this would be 11 bytes, but that would be unfair.)

trick«treat

In Chaîne, « begins a comment, and the rest is printed verbatim. In Jolf, « begins a string. Thankfully, trick does nothing harmful (10; range(input, parseInt(input)) basically), and treat is printed.

Try Jolf here!

Try Chaîne here!

They both work on my browser (firefox, latest version), but the same cannot be said for other browsers.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ I suppose being the inventory of many obscure languages has it's benefits... \$\endgroup\$ Commented Oct 26, 2016 at 1:24
  • 1
    \$\begingroup\$ Nice to see that we are getting close to soloutions pretty much only consiting out of the words themself. I wonder if anyone can reuse the tr. \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 1:25
  • 1
    \$\begingroup\$ @BrainStone I personally doubt that tr could be reused in any golf--it's a small piece of information that would take at least an operator to encode in golfing languages, then a language specific conditional. It would probably even out to either the same length, or longer. However, that's just my conjecture ;) \$\endgroup\$ Commented Oct 26, 2016 at 1:26
  • \$\begingroup\$ Let's find out. But I have to agree. A byte count of 10 or less would be insane! \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 1:31
  • \$\begingroup\$ @BrainStone, 8 bytes: codegolf.stackexchange.com/a/97580/5011 \$\endgroup\$
    – SeanC
    Commented Nov 3, 2016 at 18:09
28
\$\begingroup\$

Cubix / Hexagony, 31 bytes

t;./e;_a]"kcirt">o?@;=v=./r;\;/

Trick it out! Treat it online!

Halloween themed? Note the horrifying facts about these languages and the code:

  1. If and even if you do nothing (just put no-ops), you can never get out of the loop that is determined to be running forever...
  2. And being stuck in the middle of a 3D and a 2D programming language (Oh agony...)
  3. Inside the dimensions, you'll gradually lost where you are... where you were...
  4. And there is a =v= smiling at you which acts at no-ops in the code

Let's dig into the mystery of the hidden 31-bytes communication protocol of dimensions and terror...

trick

When the code folds or unfolds itself... That is cubified, the layout looks like this:

      t ; .
      / e ;
      _ a ]
" k c i r t " > o ? @ ;
= v = . / r ; \ ; / . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

And the main part is this part in the middle:

" k c i r t " > o ? @ .
. . . . . . . \ ; / . .

It pushes k,c,i,r,t onto the stack and o outputs and ; pops within a loop bounded by reflectors and ? which guides you depending on the value on the top of the stack...

treat

All of a sudden, the code transforms from a cube to a Hexagon. (Imagine that)

   t ; . /
  e ; _ a ] 
 " k c i r t 
" > o ? @ ; = 
 v = . / r ;
  \ ; / . .
   . . . .

And the main part is this part:

   t ; . /
  e ; _ a ] 
 . . . . . . 
. . . . @ ; = 
 . . . / r ;
  . . . . .
   . . . .

It runs t; which prints t and hits the mirror and turns its direction to NW starting from the SE corner and hits another mirror. This runs r; and wraps to e;_a and the ] brings it to the Instruction Pointer 1 which starts at corner NE pointing SE and hits / which reflects horizontally to ; then t.

Then it wraps to =, ;, and @ ends the mess.

So... What is _ doing there?

Why is it inside the t e a (the first 3 letters in the code)?

Here comes the end of the story -

it does nothing.

Does it sound like the end of a horror story?

\$\endgroup\$
2
  • \$\begingroup\$ Nice, very nice! It's difficult to create a polyglot out of two 2D languages. I like the horror story that goes along with it ;) \$\endgroup\$ Commented Oct 29, 2016 at 1:58
  • \$\begingroup\$ Not sure if this or ELF/.COM answer is more impressive. Good job! \$\endgroup\$ Commented Jul 5, 2019 at 14:53
27
\$\begingroup\$

#hell / Agony, 43 bytes

So much ><> everywhere, what is this, an April Fools challenge? Here's an answer with appropriately themed languages.

--<.<.<.<.<.$
io.write("trick")--+<~}~@+{+<

#hell is a subset of LUA which fortunately accepts io.write output calls. We use LUA's -- comments so that it only executes this fragment.

Agony is a Brainfuck derivative, which has the particularity to have its code and working memory on the same tape. The first line only prints 5 characters (10 cells) from the end of the code segment, where I encoded treat as Agony commands. LUA's comment opening -- modifies the value of a cell which isn't used.

\$\endgroup\$
2
  • \$\begingroup\$ I have to say your Halloween themed ones are the best imho. Very creative! \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 20:10
  • \$\begingroup\$ @BrainStone Thanks, I had fun making them ! \$\endgroup\$
    – Aaron
    Commented Oct 26, 2016 at 21:06
24
\$\begingroup\$

SQL / Javascript, 54 bytes

select('trick')
--a;function select(){alert("treat")}

Same approach as with my QB/JS answer: First line has the SQL statement, the second line has a 'comment' for SQL and a NOP for JS. Then, we define SQL's select statement as a valid JS function.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ That is a very smart way of combining these two languages. Have a +1! \$\endgroup\$ Commented Oct 26, 2016 at 17:35
23
\$\begingroup\$

/Brainf..k/, 143 + 3 = 146 bytes

This answer requires the -A flag to output in ASCII for Brain-Flak and luckily Brainfuck doesn't care about that flag so it doesn't affect the output in Brainfuck.

(((((()(()()()){})({}){}){}){})+++++++[<+++<(((()()()())((((({}){}){}){}){}()))[][][][]())>>-])<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>

Try it Online!

Try it Online!

How this works

The only overlap between the syntax of Brain-Flak and Brainfuck are the characters <>[]. For brain-flak this mostly means the program has to ensure an even number of stack switches <>. And for Brainfuck this means we need to avoid infinite loops caused by use of the [] monad.

The Brain-Flak code is as follows:

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

Aside from the [<<...>>] bit in the middle and the <[<>]<>[<>]<>> at the end this code is pretty par for the course as far as Brain-Flak programs go. The negative around the zero ([<...>]) is there to create a loop for Brainfuck. The inner <...> is used to move the Brainfuck to an empty cell before it encounters the [][][][] which would loop infinitely otherwise.

The Brainfuck code is as follows:

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

Aside from the aforementioned bits this is also a pretty standard program so I will spare you the details.

\$\endgroup\$
5
  • \$\begingroup\$ I like this one :D \$\endgroup\$ Commented Oct 26, 2016 at 2:35
  • 9
    \$\begingroup\$ There are a LOT more than two languages that match the regex /brainf..k/, so you should use the same header format as everyone else. \$\endgroup\$
    – mbomb007
    Commented Oct 26, 2016 at 13:52
  • 13
    \$\begingroup\$ @mbomb007 the only other language I could find that fits this regex is brainfork. Conveniently when run in brainfork this prints "TRICK" so I will leave the regex for the time being. \$\endgroup\$
    – Wheat Wizard
    Commented Oct 26, 2016 at 17:37
  • \$\begingroup\$ For brain-flak this mostly means the program has to ensure an even number of stack switches Are you sure about that? It shouldn't matter since <> is a NOP in brainfuck \$\endgroup\$
    – DJMcMayhem
    Commented Oct 26, 2016 at 21:16
  • \$\begingroup\$ @DJMcMayhem it has to end on the same stack we put everything otherwise it won't print anything. \$\endgroup\$
    – Wheat Wizard
    Commented Oct 26, 2016 at 21:17
22
\$\begingroup\$

><> / Fishing, 38 bytes

_"kcirt"ooooo;
[+vCCCCCCCC
   `treat`N

For the sake of making a ><> / Fishing polyglot.

It's my first piece of Fishing code after having played for a long time with ><>.
My first impression : as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool !

Here the code is extremely simple : ><> will only execute the first line, where _ is a vertical mirror and has no effect since the fish starts swimming horizontally. It just pushes trick on the stack then print it before stopping.
For Fishing, the _ instructs to go down. The fisherman will follow the deck that is the second line while catching the characters of the third line. These will push treat on the tape then print it, stopping as it reaches the end of the deck.

If erroring out is allowed, you could go down to 35 bytes with the following code which will throw an error when run as ><> once the trick is printed off the stack :

_"kcirt">o<
[+vCCCCCCCC
   `treat`N

You should also check my themed languages answers, #hell / Agony and evil / ZOMBIE !

\$\endgroup\$
2
  • \$\begingroup\$ Aw, I wanted to make a fish/fishing polyglot :) You beat me to it. Nice one! \$\endgroup\$
    – Emigna
    Commented Oct 26, 2016 at 9:27
  • \$\begingroup\$ +1 for "as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool !" \$\endgroup\$ Commented Oct 26, 2016 at 9:27
20
\$\begingroup\$

05AB1E/Actually, 10 bytes

"trick"’®Â

Explanation

05AB1E

"trick"     # push the string "trick"
       ’®Â  # push the string "treat"
            # implicitly print top of stack (treat)

Try it online

Actually

"trick"     # push the string "trick"
       ’®Â  # not recognized commands (ignored)
            # implicit print (trick)

Try it online

\$\endgroup\$
8
  • \$\begingroup\$ You know, I can clearly read the trick, but how is ’®Â treat?.. \$\endgroup\$ Commented Oct 26, 2016 at 8:52
  • 1
    \$\begingroup\$ Now people have known this feature. Next time we'll get questions such as "hQq3k or bvM;p polyglot"... \$\endgroup\$
    – jimmy23013
    Commented Oct 26, 2016 at 8:55
  • 3
    \$\begingroup\$ @KevinCruijssen: ’®Â is translated as "take the word with index 3757 from the dictionary", which is "treat". \$\endgroup\$
    – Emigna
    Commented Oct 26, 2016 at 9:06
  • \$\begingroup\$ @Emigna Ok... So all ~1.1M English words are accessible in 05AB1E? \$\endgroup\$ Commented Oct 26, 2016 at 9:11
  • 1
    \$\begingroup\$ @KevinCruijssen: No, there are 10k in total (each representable as 2 characters). You can find the whole list here. \$\endgroup\$
    – Emigna
    Commented Oct 26, 2016 at 9:22
16
\$\begingroup\$

Haskell / Standard ML, 56 bytes

fun putStr x=print"treat";val main=();main=putStr"trick"

Haskell view

The semicolons allow multiple declarations in one line and act like linebreaks, so we get

fun putStr x=print"treat"
val main=()
main=putStr"trick"

A Haskell program is executed by calling the main function, so in the last row putStr"trick" is executed which just prints trick.
The first two rows are interpreted as function declarations following the pattern <functionName> <argumentName1> ... <argumentNameN> = <functionBody>. So in the first row a function named fun is declared which takes two arguments named putStr and x and the function body print"treat". This is a valid Haskell function with type fun :: t -> t1 -> IO (), meaning it takes an argument of an arbitrary type t and a second one of some type t1 an then returns an IO-action. The types t and t1 don't matter as the arguments aren't used in the function body. The IO-action type results from print"treat", which prints "treat" to StdOut (notice the ", that's why putStr instead of print is used in main). However as it's only a function declaration, nothing is actually printed as fun is not called in main.
The same happens in the second line val main=();, a function val is declared which takes an arbitrary argument named main and returns unit, the empty tuple (). It's type is val :: t -> () (Both the value and the type of unit are denoted with ()).

Try it on Ideone.


Standard ML view

Standard ML is a primarily functional language with a syntax related to, but not the same as Haskell. In particular, function declarations are prefixed with the keyword fun if they take any arguments, and the keyword val if they don't. Also it's possible to have an expression at top level (meaning not inside any declaration) which is executed when the program is run. (In Haskell writing 1+2 outside a declaration throws a naked expression at top level-error). Finally the symbol for testing equality is = instead of == in Haskell. (There are many more differences, but those are the only ones that matter for this program.)
So SML sees two declarations

fun putStr x=print"treat";
val main=();

followed by an expression

main=putStr"trick"

which is then evaluated. To determine whether main equals putStr"trick", both sides have to be evaluated and both must have the same type, as SML (as well as Haskell) is statically typed. Let us first have a look at the right side: putStr is not a library function in SML, but we declared a function named putStr in the line fun putStr x=print"treat"; - it takes an argument x (this is the string "trick" in our case) and immediately forgets it again, as it does not occur in the function body. Then the body print"treat" is executed which prints treat (without enclosing ", SML's print is different from Haskell's print).
print has the type string -> unit, so putStr has the type a -> unit and therefore putStr"trick" has just type unit. In order to be well-typed, main must have type unit too. The value for unit is in SML the same as in Haskell (), so we declare val main=(); and everything is well-typed.

Try it on codingground.
Note: The output in the console is

val putStr = fn : 'a -> unit                                   
val main = () : unit                                                    
treatval it = true : bool

because in SML\NJ the value and type of every statement is displayed after each declaration. So first the types of putStr and main are shown, then the expressions gets evaluated causing treat to be printed, then the value of the expression (true as both sides of = are ()) is bound to the implicit result variable it which is then also displayed.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I always thought fun ... ... = was syntactic sugar for val rec ... = fn ... =>. But then again it's been decades since I used ML. \$\endgroup\$
    – Neil
    Commented Oct 27, 2016 at 12:31
  • \$\begingroup\$ @Neil You're right, fun is syntactic sugar for anonymous function bound with val (rec is only needed if the function is recursive) and therefore the formulation "must be prefixed" is badly chosen, I'll edit the answer. In general using fun is best-practice, especially in code golf as it's much shorter. \$\endgroup\$
    – Laikoni
    Commented Oct 27, 2016 at 13:39
15
\$\begingroup\$

Ruby / C, 64 62 51 48 bytes

#define tap main()
tap{puts(0?"trick":"treat");}

What Ruby sees:

tap{puts(0?"trick":"treat");}

The tap method takes a block and executes it once. It's a short identifier that we can create a #define macro for in C. It also allows us to put a braces-enclosed block in the shared code, even though Ruby doesn't allow {}s in most contexts.

The only falsy values in Ruby are false and nil. In particular, 0 is truthy. Thus, Ruby will print "trick."

What C sees (after the pre-processor):

main(){puts(0?"trick":"treat");}

0 is falsy in C, so C will print "treat."

2 bytes saved thanks to daniero.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Nice. You can use puts instead of printf to save two bytes \$\endgroup\$
    – daniero
    Commented Oct 26, 2016 at 17:45
  • \$\begingroup\$ Thanks! I'm so used to just always using printf in C, I've forgotten that it also has a puts function. \$\endgroup\$
    – m-chrzan
    Commented Oct 26, 2016 at 19:47
  • \$\begingroup\$ Two ideas: Can't you use something shorter for tap? And why didn't you get rid of the spaces? p ? "trick":"treat" => p?"trick":"treat" \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 19:49
  • \$\begingroup\$ tap actually serves two purposes. It's a short identifier for #define to latch onto, but it also allows me to put the braces directly in the Ruby code. {} blocks in Ruby don't work like they do in C and similar languages, but tap does take a block, and executes it once. \$\endgroup\$
    – m-chrzan
    Commented Oct 26, 2016 at 19:53
  • \$\begingroup\$ Method names in Ruby can end with a question mark, so a space is needed after p. ?<character> is a character literal, so a space is needed after the ?. \$\endgroup\$
    – m-chrzan
    Commented Oct 26, 2016 at 19:57
15
\$\begingroup\$

QBasic / JavaScript, 51 44 bytes

'';PRINT=a=>{alert("Treat")}
PRINT("Trick")

In QBasic, it prints the second line and doesn't execute the first line because it's believed to be a comment (thank you '). In JS, it calls the function PRINT, which is defined on the first line, right after the JS NOP '';.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ A very clever approach! \$\endgroup\$
    – BrainStone
    Commented Oct 26, 2016 at 8:28
15
\$\begingroup\$

Jelly / 05AB1E, 14 bytes

0000000: FE 22 74 52 69 63 6B 22 3F 37 29 FB ED 35                ."tRick"?7)..5

A fun one using Jelly's string compression.

Jelly: treat

“"tRick"?7)»ḣ5

Try it online!

05AB1E: trick

þ"tRick"?7)ûí5

Try it online!

How it works

In Jelly “"tRick"?7)» is a compressed string that returns 'Treatment dormy/ Orly awry'. ḣ5 takes the first five characters, printing Treat

In 05AB1E þ doesn't affect the program. "tRick" is a literal string. ? prints this string then the rest of the program (7)ûí5) doesn't have any effect either.

I used this to convert from Jelly's code page to 05AB1E's code page. This does the reverse in case anyone is interested.

Jelly code page is here.

05AB1E code page is here.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ First answer that actually uses the rule that arbitrary capitalization is acceptable! I like it \$\endgroup\$
    – BrainStone
    Commented Jan 17, 2018 at 5:42
  • \$\begingroup\$ @BrainStone Thanks! I think it's also one of the few (or maybe only) answer that uses the same core code in each language to produce the words 'trick' and 'treat'. In most other answers those are separate \$\endgroup\$
    – dylnan
    Commented Jan 18, 2018 at 22:23
  • \$\begingroup\$ That is correct \$\endgroup\$
    – BrainStone
    Commented Jan 19, 2018 at 5:42
14
\$\begingroup\$

ShapeScript / Foo, 13 bytes

'trick'"treat

Try it online! trick | treat

How it works

ShapeScript is parsed character by character. When EOF is hit without encountering a closing quote, nothing is ever pushed on the stack. 'trick' does push the string inside the quotes, which is printed to STDOUT implicitly.

Foo doesn't have any commands assigned to the characters is 'trick', so that part is silently ignored. It does, however, print anything between double quotes immediately to STDOUT, even if the closing quote is missing.

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

Ruby / Perl, 21 bytes

print"trick"%1||treat

Perl

Calculates "trick" % 1 which is 0 % 1 so the || sends treat to print instead, since Perl accepts barewords.

Ruby

Formats the string "trick" with the argument 1, which results in "trick" which is truthy, so the || isn't processed.

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

MATL / CJam, 17 bytes

'TRICK'%];"TREAT"

In MATL this outputs TRICK. In CJam it outputs TREAT.

Explanation

MATL

'TRICK'         Push this string
%];"TREAT"      Comment: ignored
                Implicit display

CJam

'T              Push character 'T'
R               Push variable R, predefined to empty string
I               Push variable I, predefined to 18
C               Push variable C, predefined to 12
K               Push variable K, predefined to 20
'%              Push character '%'
]               Concatenate stack into an array
;               Discard
"TREAT"         Push this string
                Implicit display
\$\endgroup\$
4
  • \$\begingroup\$ You're missing 3 characters there! (EAT) \$\endgroup\$ Commented Oct 26, 2016 at 0:18
  • \$\begingroup\$ @DestructibleWatermelon Thanks! Edited \$\endgroup\$
    – Luis Mendo
    Commented Oct 26, 2016 at 0:21
  • \$\begingroup\$ Now you are missing three in the MATL explanation! \$\endgroup\$ Commented Oct 27, 2016 at 22:09
  • \$\begingroup\$ @DestructibleWatermelon Aww. Thanks again :-D \$\endgroup\$
    – Luis Mendo
    Commented Oct 27, 2016 at 22:52
13
\$\begingroup\$

Objective-C / C, 50 bytes

puts(){printf("trick");}main(){printf("treat\n");}

Objective-C got candy and prints treat, but C didn't and prints trick.

How it works

I don't know a lot about Objective-C, but it does what we'd reasonably expect in this situation. The re-definition of puts doesn't affect the output since we never call the function, and main prints treat and a linefeed to STDOUT.

You might expect C to do the same, but at least gcc 4.8, gcc 5.3, and clang 3.7 don't.

Since we do not need the real printf (which takes a format string and additional arguments) and the string to be printed ends with a linefeed, we can use puts instead. puts is slightly faster than printf (which has to analyze its arguments before printing), so unless we redefine the function printf as well, the compiler optimizes and replaces the call to printf with a call to puts. Little does the compiler know that calling puts with argument "treat" will print trick instead!

Not including stdio.h is crucial here, since defining puts would require using the same type it has in the header file (puts(const char*)).

Finally, it is noteworthy that the call to printf in puts passes a string without a trailing linefeed. Otherwise, the compiler would "optimize" that call as well, resulting in a segmentation fault.

\$\endgroup\$
0
12
\$\begingroup\$

Jelly / pl, 12 bytes

0000000: 74 72 65 61 74 0a 7f fe 00 ba 49 fb                 treat.....I.

This is the program displayed using Jelly's code page.

treatµ
“¡ṾI»

Try it online!

This is the program displayed using code page 437.

treat
⌂■␀║I√

Try it online!

Both programs have been tested locally with the same 12 byte file, so this is a proper polyglot.

How it works

In Jelly, every line defines a link (function); the last line defines the main link, which is executed automatically when the program is run. Unless the code before the last 7f byte (the linefeed in Jelly's code page) contain a parser error (which would abort execution immediately), they are simply ignored. The last line, “¡ṾI» simply indexes into Jelly's dictionary to fetch the word trick, which is printed implicitly at the end of the program.

I don't know much about pl, but it appears that the interpreter only fetches one line of code and ignores everything that comes after it. As in Perl, barewords are treated as strings, so treat prints exactly that.

\$\endgroup\$
10
\$\begingroup\$

Batch/sh, 30 bytes

:;echo Treat;exit
@echo Trick

Explanation. Batch sees the first line as a label, which it ignores, and executes the second line, which prints Trick. The @ suppresses Batch's default echoing of the command to stdout. (Labels are never echoed.) Meanwhile sh sees the following:

:
echo Treat
exit
@echo Trick

The first line does nothing (it's an alias of true), the second line prints Treat, and the third line exits the script, so the @echo Trick is never reached.

\$\endgroup\$
10
\$\begingroup\$

sed / Hexagony 32 bytes

/$/ctrick
#$@$a</;r;e;/t;....\t;

sed

Try it Online!

The first line prints trick if there is an empty string at the end of input. (sed doesn't do anything if there isn't input, but a blank line on stdin is allowed in this case)

Example run:

$ echo | sed -f TrickOrTreat.sed
trick

Hexagony

Try it Online!

The first / redirects the instruction pointer up and the the left, so it wraps the the bottom left, skipping the text used for sed. It reuses the r from the sed code and runs a few others to no effect. The expanded hex looks like this:

   / $ / c 
  t r i c k
 # $ @ $ a <
/ ; r ; e ; /
 t ; . . . . 
  \ t ; . .
   . . . .

Output:

treat
\$\endgroup\$
7
  • \$\begingroup\$ I've seen Hexagony posts that have pictures of the execution path, is there an easy to generate those? \$\endgroup\$
    – Riley
    Commented Oct 26, 2016 at 19:17
  • \$\begingroup\$ Here it is github.com/Timwi/HexagonyColorer \$\endgroup\$
    – 0 '
    Commented Oct 27, 2016 at 1:09
  • 1
    \$\begingroup\$ Your Hexagony code prints a leading null byte. Not sure if that counts as whitespace for the purposes of this challenge. \$\endgroup\$ Commented Oct 27, 2016 at 12:05
  • \$\begingroup\$ @MartinEnder Sounds like it's allowed. Thanks for pointing that out, I always miss those for some reason... \$\endgroup\$
    – Riley
    Commented Oct 27, 2016 at 12:14
  • \$\begingroup\$ I managed to fix that while also saving a few bytes (at the cost of printing an upper case A, although you could make that less ugly by changing all letters to upper case): hexagony.tryitonline.net/… \$\endgroup\$ Commented Oct 27, 2016 at 13:21
10
\$\begingroup\$

C# / Java

This probably doesn't qualify as it doesn't run on its own, but the challenge has reminded me of a quirk in how C# and Java handle string comparison differently that you can have some fun with for code obfuscation.

The following function is valid in C# and Java, but will return a different value...

public static String TrickOrTreat(){
    String m = "Oct";
    String d = "31";
    return m + d == "Oct31" ? "Trick" : "Treat";
}
\$\endgroup\$
1
  • \$\begingroup\$ Interesting quirk indeed. \$\endgroup\$
    – BrainStone
    Commented Oct 27, 2016 at 14:04
10
+300
\$\begingroup\$

Brain-Flak / Brain-Flueue, 265 253 219 165 139 115 113 101 bytes

Includes +1 for -A

Thanks to Wheat Wizard for going back and forth, golfing a few bytes off each others code, with me.

((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){}

Brain-Flak: Try it online!
Brain-Flueue: Try it online!

Explanation:
The first section lists the values that Brain-Flak sees.
When it switches to Brain-Flueue, I start listing the values as Brain-Flueue sees them.

# Brain-Flak
(
 (((()()()))             # Push 3 twice
  ([]                    # Use the height to evaluate to 2
   (
    (({}{}))             # Use both 3s to push 6 twice
    ({}                  # Use one of those 6s to evaluate to 6
     ([((({}()())))]     # Use the other 6 to push 8 three times and evaluate to -8
      ([](({}{}){}){}{}) # Use all three 8s to push 75
     )                   # The -8 makes this push 67
    )                    # The 6 makes this push 73
   [])                   # Use the height and the 6 to push 82
  )                      # Use the 2 to push 84

# Brain-flueue
 [])     # Use the height and 3 to push 84
[()()])  # Push 82
({}()()) # 67 is at the front of the queue, so use that to push 69
{}       # Pop one from the queue
({})     # 65 is next on the queue so move to the end
({}[][]) # 74 is next, so use that and the height to push 84
{}       # Pop that last value from TRICK
\$\endgroup\$
1
9
\$\begingroup\$

PowerShell / Foo, 14 bytes

'trick'#"treat

The 'trick' in PowerShell creates a string and leaves it on the pipeline. The # begins a comment, so the program completes and the implicit Write-Output prints trick.

In Foo, (Try it Online!), the 'trick' is ignored, the # causes the program to sleep for 0 seconds (since there's nothing at the array's pointer), then "treat starts a string. Since EOF is reached, there's an implicit " to close the string, and that's printed to stdout.

\$\endgroup\$
4
  • \$\begingroup\$ Also works in J / Foo. \$\endgroup\$ Commented Oct 26, 2016 at 3:50
  • \$\begingroup\$ @ConorO'Brien Is the explanation the same? I've never used J and I'm not familiar with it. \$\endgroup\$ Commented Oct 26, 2016 at 4:03
  • \$\begingroup\$ No, this doesn't work in J. # is the copy function, and it only takes non-negative complex left arguments, not strings. The comment symbol is NB. \$\endgroup\$
    – Adám
    Commented Oct 26, 2016 at 9:03
  • \$\begingroup\$ @Adám right you are. Forgot the # \$\endgroup\$ Commented Oct 26, 2016 at 11:02
1
2 3 4 5

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.