172
\$\begingroup\$

A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

  • Gets a number (either 0 or 1) from STDIN.

  • If that number is 0, print out 0 and terminate.

  • If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

  • take input from STDIN or an acceptable alternative
    • If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program
  • must output to STDOUT or an acceptable alternative
    • If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.
  • when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory
  • the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

  • if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 snippet:

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

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
18
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$
    – Cruncher
    Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Nov 10, 2015 at 1:13
  • 1
    \$\begingroup\$ Is one allowed to print an infinite number of 1s? That is, not print out 1s forever, but print out an infinite list of 1s all at once? This would be theoretically demonstrated, but the language has no notion of printing more than once. It just generates an output. So is it okay if it runs indefinitely, but would print infinite 1s given infinite time (to finish executing)? \$\endgroup\$
    – AviFS
    Apr 26, 2020 at 1:42

494 Answers 494

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

Quipu, 20 bytes

\/1&
/\/\
1&??
>>
::
\$\endgroup\$
3
\$\begingroup\$

COMMAND.COM, 12 + 10 + 11 = 33 bytes

0.BAT:

@ECHO 0
@EXIT

1.BAT:

@ECHO 1
@1

Start COMMAND.COM with the above two files in the current directory. Then when it requests input, type either 0 or 1. Also works with CMD.EXE.

If you don't want the Microsoft version and copyright then you can use CMD /K ECHO OFF instead. I've therefore added 11 bytes for this, but subtracted 4 bytes, as you no longer need the @s at the start of each line.

If command-line arguments are acceptable and you are allowed use COMMAND /C 0 or COMMAND /C 1 then you can remove the @EXIT from 0.BAT. In that case the size is 7 + 11 + 1 + 1 = 20 bytes.

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

TeaScript, 21 16 bytes

TeaScript is JavaScript for golfing, created by user Vɪʜᴀɴ.

for(;alert×|x;);

The input is automatically stored in variable x. × (U+00D7 Multiplication Sign) is a shortcut for (x).

Try it in the online interpreter

\$\endgroup\$
2
  • \$\begingroup\$ See this line for an explanation of the bug behavior. \$\endgroup\$ Nov 4, 2015 at 0:27
  • \$\begingroup\$ @ןnɟuɐɯɹɐןoɯ Ah, yes. That explains why whil(x) did the same thing, but not whi(x). Thanks! \$\endgroup\$ Nov 4, 2015 at 1:22
3
\$\begingroup\$

O, 12 11 6 bytes

j{.o}w

When 0 is inputted, 0 is outputted and the program ends. When 1 is inputted, 1 is outputted forever.

Explanation:

j     Get input as Number
{  }w While the input is 1
 .o    Print the 1
      Print the stack when code ends, which will only contain 0
\$\endgroup\$
3
\$\begingroup\$

Binary-Encoded Golfical, 11+1 (-x flag)= 12 bytes

Hexdump of binary encoding:

00 40 02 15 14 1B 1A 17 14 24 1D

Original image:

enter image description here

Magnified 125x, with color labels:

enter image description here

Rough translation:

*p=readnum
lbl A
print *p
if *p!=0 goto A
\$\endgroup\$
3
\$\begingroup\$

Jolf

0 Bytes



I found out what to do with the zero-byte program! I made a truth machine.

0 as input

1 as input

\$\endgroup\$
6
  • 4
    \$\begingroup\$ Congrats, you have made the most boring answer on this challenge! ಠ_ಠ +1 \$\endgroup\$
    – user48538
    Jan 16, 2016 at 18:13
  • \$\begingroup\$ @zyabin101 bows thank you. \$\endgroup\$ Jan 16, 2016 at 18:13
  • \$\begingroup\$ This appears to be invalid as the second 1 seems to be a 3. \$\endgroup\$
    – Makonede
    Apr 17, 2021 at 2:48
  • \$\begingroup\$ @Makonede It worked 5 years ago. Quite frankly I'm not sure what changed. \$\endgroup\$ Apr 17, 2021 at 4:22
  • \$\begingroup\$ @ConorO'Brien Based on the JS code I figure it's just a bug. Still though, quite strange \$\endgroup\$
    – Makonede
    Apr 17, 2021 at 18:06
3
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 6 chars / 11 bytes

↻ôï|ï;

Try it here (Firefox only).

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Is the language name supposed to be "ESMin", or just five boxes? \$\endgroup\$
    – mbomb007
    Nov 4, 2015 at 17:01
  • 1
    \$\begingroup\$ ESMin in double-struck. It doesn't show up properly in some fonts, though... :( \$\endgroup\$ Nov 4, 2015 at 17:53
  • 1
    \$\begingroup\$ Ah, okay. I can only see the double-struck letters ℂ, ℍ, ℕ, ℙ, ℚ, ℝ, and ℤ. \$\endgroup\$
    – mbomb007
    Nov 4, 2015 at 22:03
3
\$\begingroup\$

Mathematica, 36 33 bytes

For[Print[i=Input[]],i>0,Print@i]
\$\endgroup\$
0
3
\$\begingroup\$

05AB1E, 5 bytes

Code:

Di[D?

Explanation:

D      # Duplicate input
 i     # If True (or 1), do
  [    # Infinite loop
   D   # Duplicate top of the stack
    ?  # Pop a, print a with no newline
\$\endgroup\$
1
  • \$\begingroup\$ Based on the date this was posted I assume implicit input wasn't a thing yet back then, but both D can be removed now to save 2 bytes. \$\endgroup\$ Jan 22, 2019 at 16:26
3
\$\begingroup\$

Batch, 35 bytes

@IF %1==0 (exit)
:l
@echo 1&goto l

Please, anyone who can golf this more is more than welcome to.

\$\endgroup\$
1
  • \$\begingroup\$ -2 bytes by removing the parentheses from the if statement \$\endgroup\$
    – T3RR0R
    Oct 31, 2021 at 15:01
3
\$\begingroup\$

Whenever, 72 bytes

From the webpage:

Introduction

Whenever is a programming language which has no sense of urgency. It does things whenever it feels like it, not in any sequence specified by the programmer.

Design Principles

  • Program code lines will always be executed, eventually (unless we decide we don't want them to be), but the order in which they are executed need not bear any resemblance to the order in which they are specified.
  • Variables? We don't even have flow control, we don't need no steenking variables!
  • Data structures? You have got to be kidding.

The official java interpreter doesn't seem to handle read() but the spec says it should work so.

1 -2,2#read();
2 defer(1) again(2) print("1");
3 defer(1||2) print("0");

The program works like this:

  • Initially 1, 2 and 3 are on the list but 2 and 3 must wait until 1 is gone.
  • When 1 is executed it removes 2 and then adds 2 back stdin times. Therefore:
    • 2 is only on the list if stdin was 1.
    • 3 must wait until 2 is gone so it can only execute if stdin was 0.
  • If 2 is executed it will add itself to the list again and print '1'.
  • If 3 is executed (meaning 2 is not on the list) it will print '0'.
  • At this point we will be in one of two states:
    • 2 will be on the list printing '1' and 3 will be perpetually waiting
    • 1, 2 and 3 will all be gone and the program will end.
\$\endgroup\$
3
\$\begingroup\$

R, 16 28 25 bytes

x=scan();while(x)cat(1);0

Edited to read x

\$\endgroup\$
1
  • \$\begingroup\$ this isn't valid, because the 0 will be printed out with an additional [1] preceding it, and the post states that the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. \$\endgroup\$
    – Giuseppe
    Mar 3, 2018 at 15:24
3
\$\begingroup\$

Scratch, 12 bytes

Script
I love how Scratch can be so self-explanatory in the right contexts.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Your list name counts as bytes \$\endgroup\$
    – anna328p
    Jul 11, 2016 at 23:36
3
\$\begingroup\$

Gaot++, 125 bytes

bleeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeet
bleeeeeeeet

Compressed: 11e4e6e13e13e13e13e9e8e6e

Try it online!

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

Churro, 100 95 bytes

{========={o}{*}======}{*}======}{={*}{={o}{={o}{={*}{={o}{======={*}{==={*}{======={*}{===={*}

Explanation

Churro is a stack-based esolang where the only syntax element is, well, churros! Or rather, ASCII-art representations of churros. An example of such a churro is {o}====}.

In Churro, each churro has three characteristics:

  1. Its orientation; whether it's facing left ({o}====}) or right ({===={o}).
  2. Its filling; whether it's filled ({*}==}) or not ({o}==}).
  3. Its tail length; the number of =s in the churro is the length of its tail.

Left-facing churros are integer literals; their tail length is their value, while their filling status is their sign. Filled churros are negative, while unfilled churros are positive.

Right-facing churros are operators; their tail length is which operator they represent, according to this table:

{{o}           pop A; discard A
{={o}          pop A, B; push B + A
{=={o}         pop A, B; push B - A
{==={o}        pop A; if A == 0, jump to churro after matching occurrence of {==={o}
{===={o}       pop A; if A != 0, jump to churro after matching occurrence of {==={o}
{====={o}      pop A, B; store B in memory location A
{======{o}     pop A; push the value in memory location A to stack
{======={o}    pop A; print A as an integer
{========{o}   pop A; print A as an ASCII character
{========={o}  read a single character from STDIN and push it to the stack
{=========={o} exit the program

Filled operator churros have the same behaviour, but peek at the stack instead of popping from it.

With that, here's the ungolfed, explained version of the Churro truth-machine:

{========={o}    read char from stdin
{*}======}       push -6
{*}======}       push -6
{={*}            push -6 + -6 = -12
{={o}            pop -6, -12; push -6 + -12 = -18
{={o}            pop -6, -18; push -6 + -18 = -24
{={*}            push input + -24
{={o}            pop -24, input + -24; push input + -48 (convert char to int)
{======={*}      print input as integer
{==={*}          if input == 0 jump to matching churro
{======={*}      print input as integer
{===={*}         if input != 0 jump back to matching churro

I'm using TheLastBanana's Haskell interpreter to interpret this. Installation instructions can be found there.

Finally, here's the "pure" version (no comments, line length 80, spaces between churros), as output by purify truth.ch:

{========={o} {*}======} {*}======} {={*} {={o} {={o} {={*} {={o} {======={*} 
{==={*} {======={*} {===={*} 

Saved 5 bytes thanks to Martin Ender!

\$\endgroup\$
1
  • \$\begingroup\$ And now I want a dulce de leche and some doughnuts... \$\endgroup\$ Aug 30, 2016 at 23:01
3
\$\begingroup\$

dc, 13 12 bytes

?[pd1=@]ds@x

Run:

dc -f truth_machine.dc <<< "1"

Adding to the diversity of languages used, I present a dc solution that works as follows:

?              # reads the input and pushes it on top of the stack
[pd1=@]ds@x    # stores the macro command [pd1=@] into register '@' and executes it
   p           # prints the value on top of the stack
   d           # makes a duplicate that is pushed on top
   1=@         # pushes 1, pops two numbers and if they are equal, the macro from
               #register '@' is executed (again), thus making an infinite cycle
\$\endgroup\$
3
\$\begingroup\$

Moorhen 1 (or original creators version 1 here), 38 bytes

The original language creator has decided to add new instructions, which would change the existing ones. Hence, this language is in Moorhen version one

op pa id el pa id el ai op id ai pi ai

Note this doesn't print if input is 1, because printing only happens at halting, so it just puts infinite ones on stack

Explanation:

Commands can be (most of) all english words, and the command they execute depends on md5 hash mod 7. I used some length two words that corresponded to each of the seven commands

re: push 0

op: increment ToS

pa: decrement ToS

el: rotate stack (place ToS on BoS)

pi: dupe ToS

id: peek TOS, skip if it is non-zero

ai: flip pointer direction

there are two main segments of code

op pa id el pa id el 
ai op id ai pi ai

op pa id el pa id el

This code, when run forwards, will have the pointer leave to the right side, with the initial value on the stack, minus one (0 -> -1, 1 -> 0). When run backwards, with [-1] as stack, it leaves the to the left side with [0] as the stack. When it leaves to the left, it will print the stack, items joined with spaces, so it will print 0. It uses "nops", commands that don't do anything under certain circumstances, or are a pair of inverses.

(the reason the comments look funny is because the interpreter ignores non-words, including real words that are hyphenated)

op pa                nop-when-running-forwards
      id el          nop-with-only-one-value-on-stack-and-running-forward
            pa       decrement-
               id el nop-with-only-one-value-on-stack-and-running-forward
                     [go to next part of code]

with all these nops forward, its essentially pa when running forward. However, backwards, with -1 on stack:

el                   nop-with-only-one-value-on-stack
   id pa             skip-pa,when-TOS-nonzero(-1,is-non-zero)
         el          nop-with-only-one-value-on-stack
            id pa    skip-pa,when-TOS-nonzero(-1,is-non-zero)
                  op increment-
                 [end,print-stack(with,-1,coming-in,print-0)]

With -1, backwards, it's essentially op (then implicit print)


The code that is at the right of that code:

ai op id ai pi ai

given -1, it will just reflect it back. Given 0, it will increment it, then enter a loop of duping ToS, which will be 1.

ai            reflect-pointer-direction-if-TOS-non-zero
   op         increment-
      id      skip-next-command-if-non-zero. This-command-skips-into-the-middle-of-a-loop:

        ai pi ai    this-is-the-loop. pointer-starts-on-pi,because-it-skipped-the-first-ai

           Here is a visualisation of how it executes
           pi       dupe-TOS (1)
              ai    reverse-if-ToS-is-nonzero (it is)
           pi       dupe-TOS (1) -again
        ai          reverse-if-ToS-is-nonzero (it is)
           pi       dupe-TOS (1) -again
           ...      this keeps happening
\$\endgroup\$
3
\$\begingroup\$

Taxi, 617 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Crime Lab.1 is waiting at Writer's Depot.Go to Writer's Depot:s 1 r 1 l 2 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 4 l 2 l.[r]Pickup a passenger going to Cyclone.Pickup a passenger going to Post Office.Go to Post Office:s 1 l 2 r 1 l.Go to Zoom Zoom:s 1 r 1 l 2 r.Go to Cyclone:w.Switch to plan "r".[z]0 is waiting at Writer's Depot.Go to Writer's Depot:n 4 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

Try it online!

There are shorter programs but they kept running out of gas. Here's the ungolfed version:

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Crime Lab.
1 is waiting at Writer's Depot.
Go to Writer's Depot: south 1st right 1st left 2nd left.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: north 1st right 2nd right 2nd left.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 4th left 2nd left.
[r]
Pickup a passenger going to Cyclone.
Pickup a passenger going to Post Office.
Go to Post Office: south 1st left 2nd right 1st left.
Go to Zoom Zoom: south 1st right 1st left 2nd right.
Go to Cyclone: west.
Switch to plan "r".
[z]
0 is waiting at Writer's Depot.
Go to Writer's Depot: north 4th left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
\$\endgroup\$
3
\$\begingroup\$

Thotpatrol, 311 219 bytes

Credit to @MickyT for shaving 92 bytes off

📡JACKING IN📡
💦DM💦 THAUGHTY JO
🕵 📧🍆 JO
🕵 🍑📧 JO
❤PRIME ASSETS❤ JO INTERROGATE ©1©
🕵 🍑📧 JO
🎧INTERCEPT MALIGNANT COMMUNICATIONS🎧
🇺🇸REPORT UNPATRIOTIC ACTIVITY🇺🇸

This is a fairly uninteresting truth machine the core structure is as follows:

input a
print a
while a == 1
    print a
end while

Here is a link to an implementation in Java: https://github.com/MindyGalveston/thotpatrol-

\$\endgroup\$
7
  • 5
    \$\begingroup\$ what in the world is this language? \$\endgroup\$
    – Riker
    Sep 4, 2017 at 21:06
  • \$\begingroup\$ This language is a pet project of mine. Its core eccentricity is that there is a finite and non-accessible list of allowed variable names. The only way to programatically allocate data is by abusing string variables and using them as databases or trial and error automatic variable naming which does not have a hard upper complexity limit. Have fun, and I'd love to answer any questions! \$\endgroup\$
    – Mr. Negi
    Sep 4, 2017 at 21:16
  • 1
    \$\begingroup\$ How is this 318 bytes? It's 243 UTF-8 bytes, or 172 characters. \$\endgroup\$ Sep 4, 2017 at 21:30
  • 1
    \$\begingroup\$ Also is Jo or Bo acceptable variable names? \$\endgroup\$
    – MickyT
    Sep 4, 2017 at 21:43
  • 1
    \$\begingroup\$ This is what I was trying to say before about a slightly different structure \$\endgroup\$
    – MickyT
    Sep 4, 2017 at 23:58
3
\$\begingroup\$

MATLAB, 39 37 bytes

Two years later, two bytes golfed off.

disp(input('')),while ans disp(1),end

This was a bit shorter than the original one, since it avoid having anything after end, thus saving a comma or semicolon, and it saves one more byte by avoiding the separate call to disp(0).

\$\endgroup\$
1
  • \$\begingroup\$ Not sure if it worked for older versions of MATLAB but it surely doesn't work for R2019b. Because input('') is used as function parameter it's never saved to ans variable. It works fine for the Octave tho. And for that it can be even shorter: disp(input('')),while 1 disp(1)end works fine. \$\endgroup\$
    – elementiro
    Jun 6, 2021 at 20:17
3
\$\begingroup\$

Duck Duck Goose, 911 bytes

duck duck duck goose

duck

duck duck duck duck duck duck goose

duck

duck duck duck duck duck duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck duck duck duck duck duck duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck duck

duck duck duck

duck duck duck duck goose

duck duck duck

duck duck

duck duck duck goose

duck



duck duck duck duck duck duck duck duck duck goose

duck duck

duck

duck duck duck duck duck duck duck duck duck duck duck goose

duck duck duck

duck duck

duck duck duck goose

duck

duck

duck duck duck duck duck duck duck duck duck goose



duck

duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck duck

duck duck goose

duck duck duck

duck

duck duck goose

duck

duck goose



duck duck duck duck duck duck duck duck duck duck goose

duck

duck duck

duck duck goose

duck duck duck

duck goose


Includes 2 trailing newlines. I can't remove the newlines, they are instructions.

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

Dreaderef, 11 bytes

5*1 1 5?8-1

Takes input from the command-line arguments. Try it online!

Explanation

This program consists of eight numbers. These numbers are grouped into instructions; each instruction consists of a label, which is the first number, and zero or more arguments, which follow the label. Instructions with different labels can have different numbers of arguments, but the parsing of instructions happens at execution time (which allows self-modification). The numbers in the program are written to the tape from position 0 at the beginning of the program; each label and argument occupies its own cell, and the instruction pointer occupies the cell at location -1.

5 *
1 1  5
? 8 -1

Dreaderef's preprocessor allows you to write aliases that stand in for numbers representing instruction labels. Using aliases makes the program look like this:

0.   numo  *
2.   deref 1  5
5.   ?     8 -1

(The leading numbers are position labels and are treated as comments.) Before the program executes, * is replaced with the input integer.

0.   numo  *

The first instruction is numo, which outputs its argument (either 0 or 1) in decimal without a trailing newline.

2.   deref 1  5

deref reads the tape at the position indicated by its first argument. It then writes that value to the tape at the position indicated by its second argument. This means that here deref copies cell 1 (the input integer and argument to numo) to cell 5 (part of the next instruction).

5.   ?     8 -1

This instruction is interesting in that the label is dynamically generated by the previous instruction (? is an alias for 0 in Dreaderef, but it is intended to convey that a given cell is uninitialized and will not be read until it is written to). During execution, it will be set to either 1 or 0 depending on the input integer. Proceeding from here requires some knowledge about what labels map to what instructions:

  • The instruction with label 0 is end, which terminates execution.
  • The instruction with label 1 is deref.

If the input integer was 0, the end instruction causes the program to terminate, and the other two numbers are ignored.

If the input integer was 1, the instruction looks like this:

5.   deref 8 -1

Cell 8 is past the end of the program, meaning that its value defaults to 0. The 0 is copied into cell -1, which is Dreaderef's instruction pointer. This means that execution jumps back to position 0, which is the start of the program. Because * is read before execution of the program, the same input (1) is reused, and the program outputs and loops again.

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

Zephyr, 41 bytes

input n
print n
while"1"=n
print n
repeat

Try it online!

A main design goal of Zephyr was that code should be readable and understandable. Looks like this holds true even when the code is maximally golfed. Mission accomplished.

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

R, 29 27 bytes

2 bytes brilliantly saved by @Giuseppe

x=scan();while({cat(x);x})1
\$\endgroup\$
2
  • \$\begingroup\$ the other R solution isn't valid, but there's another two bytes you can squeeze out of this! click here to spoil it \$\endgroup\$
    – Giuseppe
    Mar 3, 2018 at 15:38
  • 1
    \$\begingroup\$ @Giuseppe that is great. \$\endgroup\$
    – MickyT
    Mar 3, 2018 at 19:51
3
\$\begingroup\$

Rockstar, 34 Bytes

Rockstar is a quite new computer programming language, designed for creating programs that are also song lyrics. Rockstar is heavily influenced by the lyrical conventions of 1980s hard rock and power ballads.

Listen to your heart
Say your heart
While your heart is not empty
Scream it

But yes, you are right, it's longer than 34 bytes, but so poetic, I couldn't resist get some lyrics in. You could even sing it!. Here's the golfed version:

Listen to X
Say X
While X
Say X
\$\endgroup\$
3
  • \$\begingroup\$ Which interpreter are you using? Wouldn't the input be treated as a string, which is truthy? Also, would the Until X loop until X is truthy, rather than while X is truthy? \$\endgroup\$
    – Jo King
    Apr 30, 2019 at 6:50
  • \$\begingroup\$ @JoKing You are right, the golfed version was incorrect, I changed the Until loop to the While loop. (it did not change the code length). To answer your question, I use my interpreter: github.com/gaborsch/rocky - that worked the expected way, too, so it was my mistake, not the interpreter's. \$\endgroup\$
    – gaborsch
    Apr 30, 2019 at 7:01
  • \$\begingroup\$ The input is numeric in this case, so 0 is coerced to false. \$\endgroup\$
    – gaborsch
    Apr 30, 2019 at 7:03
3
\$\begingroup\$

Malbolge, 257 bytes

(aONMLKJIHGFEDCBA@?>=<;:98765FD21dd!-,O*)y'&v5#"!DC|Qzf,*vutsrqpF!Clk|ih
gfed9(T&6KoOHZYXWVUTSRQPONM]KJIHGFEDCBA@?>=<;:9876"'~g|edybav_zyxwvotsrq
pSnPlOjibKfedcba`_XA??ZYRW:UTSLQ3ONMLK.IHGFE>CBA@?"=<;:38765432s0/.n,+*)
j!&%f{"!~}|_zyxZvYnsrqpRnmlkjML:f_^GF!

Try it online!

From esolangs.org

Quite the abomination, isn't it?

In fact, this language is so horrible, I don't think anyone "programmed" this in the traditional sense. If I'm remembering correctly, this was found by a search program that basically brute-forced for possible Malbolge programs that worked as a truth machine.

\$\endgroup\$
2
  • 4
    \$\begingroup\$ The program was made by esolang's Malbolge expert Malbranche, who is amazing and certainly can program it in other ways than brute force. You may be thinking of the first Malbolge "Hello, world!", which was indeed found by search. \$\endgroup\$ May 22, 2019 at 4:07
  • \$\begingroup\$ Ah, yes. Thank you for the correction, it does make sense that a Hello World program would be much longer and more difficult. \$\endgroup\$ Sep 27, 2019 at 20:21
3
\$\begingroup\$

Rust compiler (nightly), 86 bytes

#![feature(log_syntax)]macro_rules!t{(0)=>{log_syntax!{0}};(1)=>{log_syntax!{1}t!{1}}}

(playground)

Readable version:

#![feature(log_syntax)]

macro_rules! truth_machine {
    (0) => {
        log_syntax!(0);
    };
    (1) => {
        log_syntax!(1);
        truth_machine!(1);
    };
}

truth_machine!(0);
truth_machine!(1);

Explanation

As the only way to iterate over anything other than the inputs of a macro is recursion, an infinite loop will always end in a stack overflow. I'm considering this error message "constant output of your language's interpreter that cannot be suppressed," as there's no other way to "infinitely" loop. The time for this to occur is dependent on the stack size, and thus most real-world macros will attempt to perform multiple operations per iteration to avoid this. Since this takes more space, I didn't do this. The only ways for a macro to give output are:

  • compile_error!, a builtin which will immediately terminate compilation with a message, and is thus not valid for this challenge
  • log_syntax!, an unstable builtin which will print its input to the compiler's stdout, with a newline appended
  • Returning a value from the macro directly, which directly conflicts with the concept of an infinite loop

I chose to use log_syntax!, as I decided it was the only option that would follow the rules of the challenge. However, it requires a nightly compiler, and 23 additional characters in the source to enable. The syntax of macros is pretty fixed, but one trick I found is that macros called with macro!{} instead of macro!(); do not require a semicolon after, and are thus one character shorter.

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

Jasmin, 355 321 bytes

As with the other answers I've written in Jasmin, there isn't a whole lot of golf going on here. This code is (almost) exactly the code obtained from running javap on the class file generated by intrepidcoder's java submission. The one neat golfing trick I found was avoiding the usual .limit locals line by reusing local variable 0.

Some code golf four years later

  1. Shorten the invocation of print by extending PrintStream
  2. ldc 2 is shorter than iconst_2
  3. Manipulating the stack with dup and swap is shorter than using locals variables with iload_0 and istore_0.

After these changes, the compiled class file needs to be executed with java -noverify.


.class L
.super java/io/PrintStream
.method public static main([Ljava/lang/String;)V
.limit stack 4
getstatic java/lang/System/out Ljava/io/PrintStream;
getstatic java/lang/System/in Ljava/io/InputStream;
invokevirtual java/io/InputStream/read()I
ldc 2
irem
dup2
invokevirtual L/print(I)V
dup
ifgt $-5
return
.end method
\$\endgroup\$
3
  • \$\begingroup\$ Would it be any shorter to put the code in an initializer block and not have a main method? \$\endgroup\$
    – feersum
    Nov 3, 2015 at 22:44
  • 1
    \$\begingroup\$ @feersum I've never been able to get static blocks to work using java version "1.8.0_60". I think static block are only accepted by java in version 1.6 and earlier. I don't have the correct version to test it so, I'll leave my answer as is for now. \$\endgroup\$ Nov 3, 2015 at 23:03
  • \$\begingroup\$ +1 for golfing this 4 years later \$\endgroup\$
    – EdgyNerd
    Aug 27, 2019 at 6:21
3
\$\begingroup\$

Acrostic, 89 45 bytes

-44 bytes by running the initial input command backwards to output the zero (thanks Jo King for the idea!).

     R
DOUBLE
  N  A
PROVIDED
R
I
NIL
T
END
D

Try it online...? (This esolang has no official online interpreter; that link takes you to a repl.it link with my own unofficial Python interpreter loaded in, complete with the truth machine program. If I can find/make a more proper online interpreter, I'll link that instead.)

Acrostic is an esolang designed by Mercerenies for which programs take the form of crosswords, which are traversed word-by-word during program execution.

First, END is run backwards, which starts the program. PRINTED is then run backwards, which will take a numerical input and push it onto the stack. If the top of the stack is 0, the PROVIDED branch is not taken, and instead NIL is run (which does nothing). Because there are no other words to run from there, PRINTED is executed forwards, and then END is executed, ending the program. If, however, the top of the stack is nonzero, the PROVIDED branch is taken, READ is run backwards (outputting the number), DOUBLE is executed backwards (pushing -2), UNO is executed forwards (pushing 1), and PROVIDED is executed (because the top of the stack is nonzero), looping this section forever.

It took me much trial and error to get an Acrostic truth machine this short, though IMHO it is a very clean and compact example. If only this language were easier to golf...

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the idea about reusing the read to print the zero @JoKing, I have a 46-byte solution now that I'm playing around with. \$\endgroup\$ Oct 1, 2020 at 19:58
3
\$\begingroup\$

Vyxal, 4, 3 bytes

-1 thanks to @Aaron Miller (uses implicit input for the 1s)

[{₴

Try it Online!

\$\endgroup\$
3
1 2 3
4
5
17

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.