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

0
\$\begingroup\$

Lua, 38 bytes

x=io.read()repeat print(x)until x~='1'

Try it online!

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

Turing Machine But Way Worse, 139 bytes

0 0 0 1 1 0 0
0 1 0 1 2 0 0
1 2 1 1 3 0 0
1 3 1 1 4 0 0
0 4 0 1 5 0 0
0 5 0 1 6 0 0
0 6 0 1 7 0 0
0 7 0 1 8 1 1
1 7 1 0 8 1 0
0 8 0 1 7 1 0

Try it online!

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

C (gcc), 52 bytes

main(i){for(scanf("%d",&i);i;)puts("1");puts("0");}

-27 bytes thanks to JoKing
-2 bytes thanks to Jonathan Frech
Try it online!
I though I'd try something other than my primary language (Java).

\$\endgroup\$
  • \$\begingroup\$ @JoKing implicit int type? That's good to know. \$\endgroup\$ – Benjamin Urquhart Mar 10 at 4:23
  • \$\begingroup\$ You can even use main(i). \$\endgroup\$ – Jonathan Frech Mar 10 at 9:02
  • \$\begingroup\$ Furthermore, while(...) is equivalent to for(;...;), making space for your scanf and allowing for the semicolon to be dropped. \$\endgroup\$ – Jonathan Frech Mar 10 at 9:04
  • \$\begingroup\$ @JonathanFrech thanks. You can probably tell that I don't know C very well :) \$\endgroup\$ – Benjamin Urquhart Mar 10 at 11:19
0
\$\begingroup\$

Eukleides, 40 bytes

a=number();for i=0to 0;print a;i=i-a;end

Pretty straightforward. number() takes in a number as input. For loop seems to be the golfiest means of looping for this task. While loop skips the i=i-a; but requires two prints.

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

C++ (gcc), 65 bytes

#include<cstdio>
int main(){for(int c=getchar();putchar(c)-48;);}

Try it online!

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

VTL-2, 25 bytes

1 A=?
2 ?=A
3 #=4-2*A

Line numbers always take up two bytes in VTL, hence the byte count discrepancy.

This should work in VTL-1 as well, but I don't have an interpreter to ensure that is the case. I've tested this under a VTL-2 interpreter running on an Altair 8800 simulator, both sourced from here. Here's a PDF manual for VTL-2.

VTL was a small (<800 bytes!) and simple language for the Altair 8800 and 680 machines. Its creative use of system variables helped to keep it small. ? represents both input and output. Note that this truth machine outputs no line breaks, as those always need to be manually printed (by printing an empty string, ?=""). # represents line number, and can be used to retrieve the current line number or assigned to form a goto. That should be enough to make this truth machine make sense...

1 A=?         ) Put input into variable A
2 ?=A         ) Print the contents of variable A
3 #=4-2*A     ) Goto 4-(2*A)... So, (nonexistent) line 4 if input was 0
              ) Or back to line 2 if input was 1. Yes, `)` is the comment character.
\$\endgroup\$
0
\$\begingroup\$

Aheui, 28 bytes

붕박누망홰
차봇멍보

Try it online!

Additionally, I found bug of TIO with Aheui : Aheui is befunge-like, but initial direction is up-to-down, but TIO's initial direction is right-to-left, so my original code got error.

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

EZLang, 105 bytes

MEM(0)
SET(-1)
MEM(1)
GET()
SET(-1, 1)
JLZ(12)
SET(1, 1)
MEM(1)
PRT()
MEM(0)
JLZ(8)
SET(1, 1)
PRT()
HLT()

Self-made esolatic language.

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

Pip, 7 bytes

IqW1P1i

Try it online!

explanation:

If(q) // q is input
    While(1) {
        print(1);
    }
output 0  // i is initialized to 0, but this stops it from being confused for "10"
\$\endgroup\$
0
\$\begingroup\$

33, 4 bytes

O[o]

Explanation:

0 input:

O    | Get input
  o  | Print it
 [ ] | Loop ends because accumulator is 0

1 input:

O    | Get input
 [ ] | While the accumulator is 1 (forever)
  o  | Print it
\$\endgroup\$
0
\$\begingroup\$

Befunge-93, 7 bytes

&>:.:_@

Try it online!

_ is the horizontal if in befunge - conveniently, it sends the IP right if the top of the stack is 0 (so it hits @ to end the program), and left if the top of the stack is nonzero (which puts it in an infinite loop).

\$\endgroup\$
  • \$\begingroup\$ This seems to be a duplicate of this answer. \$\endgroup\$ – Mr. Xcoder Aug 26 at 19:06
0
\$\begingroup\$

Runic Enchantments, 6 bytes

i:?@:$

Try it online!

? is a conditional jump command that skips n instructions where n is a value popped from the top of the stack. If that value is 0, we dump the stack and terminate. If its 1 we skip that instruction and print the value, leaving a copy on the stack, then loop. i does nothing if there is no more input to read.

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

JavaScript, 32 bytes

do{alert(x=x||prompt())}while(x)
\$\endgroup\$
0
\$\begingroup\$

Unsuspected-hangul, 187 bytes

ㅀㄱ ㄱㅇㄱ ㅅㅅㅎㄴ ㄳㅎㄴㅎ ㄱㅀㄷ ㄱㅇㄱ ㅁㅈㅎㄴ ㅈㅀㄴ ㄱㅇㄴ ㄴㅇㅎㄴ ㅂㄱㅎㄱ ㄳㅎㄴ ㄱㅇㄴ ㄴ ㄴㅎㄷㅎㄷㅎ ㄱㅀㄷㅎ ㄱㅀㄷ

You can try it here

Note that it use pop-up for standard output, and you have to close tap to terminate the program.

How does it work?

ㄹ ㅎㄱ [ㄱㅇㄱ ㅅㅅㅎㄴ ㄱㅅㅎㄴ ㅎ] ㄱㄹㅎㄷ bind(input(), int)
    [def print_and_recursion(x) num -> IO(nil)
    ㄱㅇㄱ ㅁㅈㅎㄴ ㅈㄹㅎㄴ print(str(x))
        [def recursion_part(not_used) nil -> IO(nil)
        (ㄱㅇㄴ ㄴㅇ ㅎㄴ) print_and_recursion(x)
        (ㅂㄱㅎㄱ ㄱㅅㅎㄴ) IO(nil)
        (ㄱㅇㄴ ㄴ ㄴㅎㄷ) ㅎㄷ if(x == 1) then... else...
    ㅎ]
    ㄱㄹㅎㄷ bind(print(str(x)), recursion_part)
ㅎ]
ㄱㄹㅎㄷ bind(bind(input(), int), print_and_recursion)

Unsuspected-hangul(평범한 한글) is Korean character-based functional esolang.

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

Gaia, 3 bytes

:p↺

Try it online!

Explanation

  ↺  While...
:    Duplicating the top of stack leaves a true value on top:
 p   Print the top of the stack

Input is taken implicitly in Gaia. Every iteration leaves the stack empty, but if there is no input left when it attempts to grab some, it simply takes the most recently given input again.

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

Ruby, 22 bytes

->(n){n==0?0:loop{p1}}
\$\endgroup\$
-2
\$\begingroup\$

Python 2, 43 42 41 bytes

x=raw_input();print x
while x>'0':print x

Got a syntax error at the while loop if I tried to run it as a one-liner. Not really sure why.

EDIT: Knocked off a semicolon.

Knocked off ANOTHER semicolon that I put on there because I've been looking at C too much lately.

\$\endgroup\$
  • 3
    \$\begingroup\$ You could use x=input() and then x>0 \$\endgroup\$ – Cyoce Sep 20 '16 at 17:41

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.