149
\$\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\$
  • \$\begingroup\$ Can we assume that the program halts when the processor finishes executing the written code, for a machine code entry? \$\endgroup\$ – lirtosiast Nov 3 '15 at 16:58
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ – Cruncher Nov 3 '15 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ – a spaghetto Nov 3 '15 at 17:38
  • 4
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ – Addison Crump Nov 6 '15 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ – Mooing Duck Nov 10 '15 at 1:13

377 Answers 377

3
\$\begingroup\$

Shakespeare Programming Language, 189 bytes

.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ford:
Listen to thy heart.
Scene II:.
Ford:
Open thy heart.Is cat as big as you?If so, let us return to scene II.
[Exeunt]

Ungolfed:

The Construction of a Truth-Machine in Denmark.

Hamlet, the input.
Ophelia, who orders him around.

Act I: A truth-machine.

Scene I: In which Hamlet learns that all he needs, he can find in his heart.

[Enter Hamlet and Ophelia]

Ophelia:
  Listen to thy heart.

Scene II: In which Ophelia proclaims her doubts about Hamlet.

Ophelia:
  Open thy heart. Is my lover as fair as thee?
  If so, let us return to scene II.

[Exeunt]

I'm using drsam94's SPL compiler + GCC to compile this.

To test:

$ python splc.py tm.spl > tm.c
$ gcc tm.c -o tm.exe
$ echo 0 | ./tm
0
$ echo 1 | ./tm
1111111111111111111111111111111111111111111111...
\$\endgroup\$
  • \$\begingroup\$ Do you have the link for the Python implementation of SPL? looking to work on a JavaScript fork of it... \$\endgroup\$ – WallyWest Aug 30 '16 at 23:03
  • \$\begingroup\$ @WallyWest Here it is! \$\endgroup\$ – Copper Aug 30 '16 at 23:07
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\$
  • \$\begingroup\$ And now I want a dulce de leche and some doughnuts... \$\endgroup\$ – WallyWest Aug 30 '16 at 23:01
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\$

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\$
3
\$\begingroup\$

Deoxyribose, 18 bytes

Updated for the new v3 spec

ATGGAGAAGAGCATAAAT

Explanation:

ATG                         ATA (*)
GAG Glu     Dupe            TGG Trp     Power
AAG Lys     Pop             AGA Arg     Unipop
AGC Ser     Jump if <= 0    AGA Arg     Unipop
ATA *                       GCA Ala     Modulo
AAT Asn     Loop            TAA End
  • Execution starts at the initial ATG.
  • The top element of the main stack is duplicated & printed, then If the value is less than or equal to zero, jump to the ATA formed by the Asn and the start codon (remember, the code is circular), then run through a series of no-ops, including printing some non-printable characters. If the value is greater than 0, loop back to the start.

If you don't like the ugly sequence of no-ops, adding ATG to the end to make the loop target explicit results in a clean termination immediately after the jump, for three more bytes.


Deoxyribose 2, 21 bytes

ATGTGAGAAAAATCTAACTTA

Explanation:

ATG Start                           TAA Stop ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
TGA Block size = 56               ┏ TGT Cys     Destination of Asn ┆
GAA Glu     Duplicate             ┃ GAG Glu     Duplicate          ┆
AAA Lys     Pop as int            ┃ AAA Lys     Pop as int         ┆
TCT Ser     If >= 0, jump to Thr ┐┞ AAT Asn     Jump back to Cys   ┆
AAC Asn     Jump back to Cys ────┼┘                                ┆
TTA                              └─ ACT Thr     Destination of Ser ┆
                                     └┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘

This is the first challenge on this site ever answered in this language (since it's only a week old), but I think it's a good showcase of what the language can do so I'll provide a bit of an explanation of what's going on. If you happen to be really interested, the spec, a Python-based interpreter, and additional (less golfed) examples are on GitHub.

Deoxyribose is a stack-based language with a small instruction set and a syntax based on DNA. Execution takes place on a circular stretch of DNA, translating 3-digit "codons" into proteins, each of which corresponds to either

  • an operation on one or both of the stacks, or
  • a (perhaps conditional) jump to a particular sequence elsewhere in the code.

These jumps can lead to frameshifts, where the read head is moved a non-integer number of codons and the same bit of code ends up doing two totally different things at different times. The degenerate nature of the genetic code makes it possible (and fun!) to use this to your advantage.

\$\endgroup\$
  • \$\begingroup\$ I love this language concept! \$\endgroup\$ – histocrat May 2 '18 at 21:45
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\$
  • \$\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 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 at 7:01
  • \$\begingroup\$ The input is numeric in this case, so 0 is coerced to false. \$\endgroup\$ – gaborsch Apr 30 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\$
  • 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\$ – Ørjan Johansen May 22 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\$ – ThePlasmaRailgun Sep 27 at 20:21
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\$
  • \$\begingroup\$ Would it be any shorter to put the code in an initializer block and not have a main method? \$\endgroup\$ – feersum Nov 3 '15 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\$ – ankh-morpork Nov 3 '15 at 23:03
  • \$\begingroup\$ +1 for golfing this 4 years later \$\endgroup\$ – EdgyNerd Aug 27 at 6:21
2
\$\begingroup\$

tinylisp, 36 bytes

This is a language that I'm basing an upcoming challenge on. The spec in the challenge doesn't include the disp function, but the reference implementation does.

(d M(q((x)(i x(i(disp x)0(M x))0))))

Defines a function M that takes an argument x (the closest that the language has to input). If x is falsey, we return 0, which is printed. If x is truthy, we want to display x and then recurse. There isn't any equivalent to Common Lisp's progn in the language, so the best way to do this is to use the disp call as the condition of an if. The result is falsey, thus putting the recursive call (M x) in the else branch.

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

Sisi, 22 bytes

Sisi doesn't have any way to take user input, so the number is expected to be stored in the variable x (presumably on line 1).

2 print x
3 jumpif x 2

Pretty straightforward: print the number, and keep doing so as long as it's 1.

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

Stuck, 9 Bytes

Stuck has a while loop function (which I never added to the docs on Esolangs, but it has existed for a little over 2 months) which makes this possible. It wasn't before this as far as I know :P.

ip"1="'ph
\$\endgroup\$
  • 2
    \$\begingroup\$ Dammit I was trying to make a truth machine in Stuck but couldn't figure out how to do it without a while loop \$\endgroup\$ – a spaghetto Nov 3 '15 at 20:15
  • \$\begingroup\$ @quartata Sorry about that :P Whenever I get enough free time I will update the documentation. \$\endgroup\$ – Kade Nov 3 '15 at 20:20
2
\$\begingroup\$

Beam, 25 23 13 bytes

rSn(`)>@<
H@<

Try it in the online interpreter! (Warning: it may crash your browser with an input other than 0.)

Beam is a 2D language, based on the concept of a beam of light moving through the 2D source code. Beam is oriented around two main memory values: one held by the beam, and one called the "store". Here are the commands used, in order:

  • r - Set the beam to the next ASCII code in the input. (48 for 0, 49 for 1)
  • S - Set the store to the beam.
  • n - If beam != store, point the beam downward. Does nothing the first time.
  • ( and ) - If store != 0, point the beam right/left, respectively.
  • ` - Decrement the store by 1.

Now, the beam enters (`) from the left, and bounces back and forth until the store reaches 0. If the store's initial value is 48 (0), it will exit to the left, traveling through these chars:

  • n - If beam != store, point the beam downward. This time, since the beam is 48 and the store is 0, it does its job.
  • < - Unconditionally point the beam to the left.
  • @ - Output the beam as an ASCII character. Prints 0.
  • H - Halt the program.

However, if the store's initial value is 49 (1), it exits the loop to the right, and runs through this code:

  • > - Unconditionally point the beam to the right.
  • @ - Output the beam as an ASCII character. Prints 1.
  • < - Unconditionally point the beam to the left.
  • @ - Output the beam as an ASCII character. Prints 1.
  • > ...

...and so on until the end of time (or until your browser crashes).

Thanks to @MickyT for this awesome layout!

P.S. If you want to learn more about Beam, check out and vote on this post!

\$\endgroup\$
  • \$\begingroup\$ +1 I like it, didn't think I could shorten it, but here's a slightly shorter version. 2 Lines rSn(`)>@< and H@< for 13 \$\endgroup\$ – MickyT Nov 3 '15 at 22:16
  • \$\begingroup\$ @MickyT Holy cow, that's brilliant! I'll update in a sec \$\endgroup\$ – ETHproductions Nov 3 '15 at 22:18
2
\$\begingroup\$

JavaScript (ES6), 77 73 64 61 bytes

x=prompt()==1;j=a=>{if(x)setTimeout(j,9);console.log(+x)};j()

This program doesn't crash your web browser!

Explanation:

x = prompt() == 1;             // this makes sure input is 1 or not while defining
j = a => {                     // es6 arrow function
  if (x)                        // if x is 1
    setTimeout(j, 9);            // make sure to do this function again in 9ms
  console.log(+x);              // log the number
};
j();                           // call j
\$\endgroup\$
  • \$\begingroup\$ Better version: x=prompt()==1;j=()=>{if(x)requestAnimationFrame(j);console.log(x?1:0)};j() \$\endgroup\$ – anOKsquirrel Nov 3 '15 at 19:53
  • \$\begingroup\$ Even better, replace j=()=> with j=a=> \$\endgroup\$ – anOKsquirrel Nov 3 '15 at 19:59
  • \$\begingroup\$ Actually, using x=prompt(); is shorter, but you have an x==1?1:0 that could just be x. That leaves x=prompt();j=a=>{if(x==1)requestAnimationFrame(j);console.log(x)};j() at 69 bytes. However, instead of using requestAnimationFrame you could use a setTimeout, which is shorter and leads to x=prompt();j=a=>{if(x==1)setTimeout(j,10);console.log(x)};j() at 69. Oh crap! That would mean that JS beats Stack! D: \$\endgroup\$ – anOKsquirrel Nov 3 '15 at 20:12
  • \$\begingroup\$ Haha. The reason I use x==1?1:0 is so that if the user inputs "true" it counts as 0. \$\endgroup\$ – Florrie Nov 3 '15 at 20:50
  • \$\begingroup\$ (oh my, it's liam4! hey!) But you don't need to. The only inputs needed 1 and 0. \$\endgroup\$ – anOKsquirrel Nov 3 '15 at 21:01
2
\$\begingroup\$

Brainfuck, 54 bytes

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

Explanation:

+++[>++++[>++++<-]<-]>>> Set a register to 48 (ASCII 0), using multiplication to reduce the byte count (3*4*4), then set the pointer to the next instruction

,. Receive and print a line of input

[>+<<[>>-<<-]>>>+<<-]Set the next register to be a numerical value, and the one after to represent the ascii output value

> Move the data pointer to the numerical register

[>.<] While the numerical register is not 0, print the ascii register

\$\endgroup\$
  • \$\begingroup\$ I already have a shorter BF program, but just so you know, 48 can be made shorter. See this helpful page. \$\endgroup\$ – mbomb007 Nov 3 '15 at 21:44
  • \$\begingroup\$ Thanks. Yeah, I didn't see your program before I posted mine, must have missed it when scrolling through. \$\endgroup\$ – Ethan Nov 3 '15 at 22:01
  • \$\begingroup\$ Try running the code snippet contained in the question. \$\endgroup\$ – mbomb007 Nov 3 '15 at 22:12
2
\$\begingroup\$

PoGo, 10 bytes

ifpouftogo

Explanation:

  • if - accept numerical input and place the result into the current memory cell
  • po - add current position in code to the top of the po stack
  • uf - output the value in the current memory cell as a number
  • to - execute the following command only if the value in the current memory cell is >0
  • go - pop the most recent po location off the stack and jump there

The "po" stack is a call stack used for flow control.

The program in pseudo code:

read int x
do:
    print x
while x > 0
\$\endgroup\$
2
\$\begingroup\$

brainfuck, 20 bytes

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

This requires an interpreter that exits with an error upon stepping out of bounds with < (such as this one). Stepping over the left edge in case of an even value was the easiest way I found to do a parity test. I wouldn't be surprised if it could be a couple of bytes shorter.

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

Batch, 44 bytes

@set/p n=
:a
@echo %n%
@if %n%==1 goto :a

Explanation

  • set /p reads from stdin into a variable
  • :a is a GOTO marker, because batch does not have while loops

The rest should be obvious: output the variable n and if n is 1, repeat.

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

Labyrinth, 6 bytes

?|:!:/

In the case of a 0 input, this terminates with an error. For a beautiful solution which exits cleanly, see Sp3000's answer.

Since the code is linear, the instruction pointer will move back and forth on the code (it will turn around when hitting a dead end, executing the instruction at the end only once). So what is happening?

?  Read the input as an integer.
|  Compute the bitwise OR of the top two stack elements (there is an infinite supply of
   zeroes at the bottom). This is a no-op at this point.
:  Duplicate the input.
!  Print it as an integer.
:  Duplicate the input.
/  Divide the input by itself. If the input was 0, the interpreter will throw an error,
   polluting STDERR, but we can ignore that. STDOUT remains unchanged. If the input was
   1, then 1/1 just yields 1 again and execution continues leftwards.
:  Duplicate the 1.
!  Print it.
:  Duplicate the 1.
|  Bitwise OR between 1 and 1 gives 1.
?  Try reading another integer. But we're at EOF, so this pushes 0.
   We're in a dead end, so the IP turns around and moves back to the right.
|  Bitwise OR between 1 and 0 gives 1.
   At this point, the state is exactly the same, as the first time we hit |, so from here
   on it's an infinite loop, printing two 1s per iteration.
\$\endgroup\$
2
\$\begingroup\$

VBA, 54 48 Bytes

Sub f(u):Do:Debug.Print u:Loop While u>0:End Sub

Look Guys, VBA can fit on one line(almost) and be hard(ish) to read like all the other Languages.

Debug.Print could be Msgbox but I feel that isn't the Spirit of the challenge and you really don't want Never ending pop-ups

Old Code

Sub f(u):Do:Debug.Print u:If u=0 Then End
Loop:End Sub
\$\endgroup\$
  • \$\begingroup\$ Using ActiveSheet.Range("A1") as your input and running in the Immediate Window, you can reduce to 31 bytes: ?[A1]:Do Until[A1]=0:?[A1]:Loop \$\endgroup\$ – Chronocidal May 9 '18 at 9:40
  • \$\begingroup\$ For sure. Any of my VBA answers are designed not to run in immediate and do not use sheets. VBA can for sure be shortened by using those methods and I encourage you to explore the possibilities. But at the time there were few to no VBA responses so I limited myself to Subs only. \$\endgroup\$ – JimmyJazzx May 9 '18 at 10:15
2
\$\begingroup\$

FORTH, 44 bytes 39 bytes 31 bytes

Edit:

As suggested by @Nate Eldredge, we can shorten the code, if we allow extra spaces in the output. This program is 31 bytes long:

: P BEGIN DUP . ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

First version:

: P BEGIN DUP 48 + EMIT ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

Explanation:

We expect the value 'b' of 0 or 1 on the stack.

: P       -- beginning a word P                          ( b ) 
BEGIN     -- starting a loop                             ( b )
DUP 48 +  -- creating an ASCII code for the character    ( b  b+48 )
EMIT      -- echoing the character                       ( b )
?DUP      -- dup'ing the value if non-zero               ( 1  1 ) or ( 0 )
0=        -- testing if the value is zero                ( 1 FALSE) or ( TRUE )
UNTIL     -- end of the loop if true                     ( 1 ) or ( - )
;         -- finishing the word

If I take the challenge seriously, FORTH has Standard I/O capabilities, but it is natural in FORTH to take the input from the stack.

If I use the STDIO feature, the code looks like this (44 bytes)

: P KEY BEGIN DUP EMIT DUP 48 = UNTIL DROP ;

Sample run:

P

(Note, that in my environment the standard input was buggy)

\$\endgroup\$
  • 2
    \$\begingroup\$ My FORTH is rusty, but wouldn't it be easier and shorter to use . instead of 48 + EMIT? \$\endgroup\$ – Nate Eldredge Nov 5 '15 at 19:45
  • \$\begingroup\$ @NateEldredge . puts an extra space after the number, otherwise it's OK. I've read in some answers that it may be acceptable. If that's the case we can shorten the code. I'll update the answer. \$\endgroup\$ – gaborsch Nov 5 '15 at 23:12
2
\$\begingroup\$

MIPS asm, 24 bytes

main:
li $v0, 5  # load read int
syscall  # exec read int, stores value in $v0
move $a0, $v0  # store in $a0
li $v0, 1  # load print int
loop:
syscall  # print $a0
bgtz $a0, loop  # loop while $a0 is greater than zero

Had to learn MIPS recently, might as well do something fun with it.

\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

Marbelous, 23

This version doesn't terminate after the zero is printed, but that should be alright:

..}0
../\//
>0
}0
+O
+O

Old version:

}0@0
\\
../\+O
>0\/+O
@0

It doesn't add a newline between each 1, but whatevs.

\$\endgroup\$
  • 2
    \$\begingroup\$ You need to terminate if your language is at all capable of terminating. \$\endgroup\$ – lirtosiast Nov 18 '15 at 3:31
2
\$\begingroup\$

Rotor, 4 bytes

{}|

Contains an unprintable, so here's a hexdump:

0000000: 7b1b 7d7c                                {.}|

Explanation:

        implicit -- evaluate and push input onto stack
{       beginning of block
  ^[    prints the top value of the stack (without popping it)
}|      execute block while top value is truthy
        implicit -- print stack
\$\endgroup\$
2
\$\begingroup\$

Python 2- 64 bytes

x=input()
if x==0:print"0"
elif x==1:
 while True: print"1"
\$\endgroup\$
  • \$\begingroup\$ A trick you can exploit in Python is that 0 is the same as False and anything but 0, including 1, is True. This generally holds in most programming languages \$\endgroup\$ – bioweasel Nov 1 '16 at 20:00
2
\$\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\$
  • 3
    \$\begingroup\$ Congrats, you have made the most boring answer on this challenge! ಠ_ಠ +1 \$\endgroup\$ – user48538 Jan 16 '16 at 18:13
  • \$\begingroup\$ @zyabin101 bows thank you. \$\endgroup\$ – Conor O'Brien Jan 16 '16 at 18:13
2
\$\begingroup\$

Detour, 2 bytes

,~

Try it online!

, will print a value then push it to the next cell.

~ is a filter, so it will push a value IFF it is greater than 0.

Cells wrap around the edges.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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