170
\$\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

475 Answers 475

1
12 13 14 15
16
0
\$\begingroup\$

Knight, 13 11 bytes

New method with suggestions from the language's author:

I+0P W1O1O0

Try it online!

# Read a string, coerce to number by adding 0, and check if non-zero
: IF (+ 0 PROMPT) {
    # if it was non-zero, loop printing 1 forever
    : WHILE 1 {
        : OUTPUT 1
    }
    # else output 0 and exit.
    {
        : OUTPUT 0
    }

Old version which I wrote on my own:

;=wP;W+0wO1O0

There are a few ways to do this. Decided this way because of a certain theme.

Ungolfed version:

# Read string into input
; = input PROMPT
# Coerce input to a number by adding 0, and loop while not 0
; WHILE (+ 0 input) {
    # Output 1 and a new line
    : OUTPUT 1
    # this is an infinite loop
}
# Otherwise, output 0 and a new line, and quit
: OUTPUT 0

If we allow excess newlines, this is an arguably superior program:

;=wP;W+0wOwOw

However, this prints two new lines because PROMPT includes the trailing newline. 😔

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

Barrel, 10 bytes

This makes use of the fact that the input will be only 0 or 1:

λn?a:#∞n

Explanation:

λ        // input into the accumulator
 n       // print the accumulator
  ? :    // if-else statement (auto-closes to '?a:#∞n::')
   a     // if the accumulator evaluates to truthy (i.e. non-zero)...
     #∞  // ...loop forever...
       n // ...implicitly print the accumulator...
         // ...else do nothing

In other news, I really should make a custom charmap for barrel. With a custom charmap, I could shave off 3 bytes.

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

Ocaml, 46 bytes

let a=read_int()in while print_int a;a=1 do 0

urk the functions name and the control flow takes a lot of chars. The trick since there is no do-while is to put the print directly in the condition (sometime ago when I did that in a course lab, the teach called me a "connoisseur of monstrosities" (approx tl))

The 0 in the end causes a warning, so you need to disable werror.

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

sed, 13 bytes

:l;s/1/1/p;tl

Try it online!

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

Squire, 47 bytes

x=inquire()whence l proclaim(x+" ")if"0"!=x{l:}

Whilst some languages have a goto keyword, Squire useth whence, the opposite. One might call it a comefrom. Squire also containeth a normal loop with whilst, but alas, it is impossible to useth this without enscribing proclaim twice.

If we accompany whence with if, we can create a loop that some call do-whilst.

Ungolfeth:

# Inquire a line from ye standard input
x = inquire()
# Set a whence point
whence loop
# Proclaim x, followed by a space, to ye standard output
proclaim(x + " ")
# If x is not "0"
if "0" != x {
    # Loopeth ad infinitum
    loop:
}

Methinks this language is ridiculous. 😂

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

Nim-Lang, 72, 64, 49, 41 (credits to @hyper-neutrino and @Jo King) bytes

var a=readChar(stdin)
while a=='1':echo 1
echo 0

Version with if-statement, with suggested edits:

if readChar(stdin)=='0':echo 0
else:
  while true:echo 1
\$\endgroup\$
4
  • 1
    \$\begingroup\$ I'm not familiar with Nim, but could you remove some whitespace (e.g. after the two colons)? Also, does if'0'==a work instead? Also, is while 1 allowed? That's a trick in Python but I don't know if Nim accepts that. Finally, could you use an if-else instead, or even better, if a is 1, while loop, and then just echo 0 at the end, since the while loop will never terminate anyway? \$\endgroup\$
    – hyper-neutrino
    Jun 27, 2021 at 22:32
  • 1
    \$\begingroup\$ No, while 1: is not allowed, unfortunately. However, the space can be removed. Thanks for the tip. \$\endgroup\$
    – Qaziquza
    Jun 28, 2021 at 2:42
  • 1
    \$\begingroup\$ do you actually need to assign to a? can you just use readChar(stdin) in the condition? \$\endgroup\$
    – Jo King
    Jun 28, 2021 at 3:37
  • \$\begingroup\$ Oh, right. Sorry, stupid of me. \$\endgroup\$
    – Qaziquza
    Jun 28, 2021 at 20:07
0
\$\begingroup\$

n/t/roff, 27 bytes.

.de a
\\$1
.if \\$1 .a 1
..

Defines a macro a.

Usage

.a 0
.a 1

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ No wait I need to modify to accept from STDIN, not from macro argument. \$\endgroup\$
    – user100411
    Aug 19, 2021 at 2:52
  • \$\begingroup\$ How the hell can I do so? \$\endgroup\$
    – user100411
    Aug 19, 2021 at 12:13
0
\$\begingroup\$

Pure Bash, 32 + 1 = 33 bytes

The 1-byte penalty is for filename specification; the following program must be saved as x.

((x))||read x
echo $x
((x))&&. x

Try it online!

Tracing how it works

  • The variable x is not initialized.
  • ((x)) evaluates to ((0)): command is failure.
  • So read x is done.
  • Then echo $x.
  • Final line is for branching.
    • If x is zero, the program ends.
    • If x is one, . x is done.
      • It loads the file x: the program itself.
      • First command evaluates to ((1)) so no more reading.
      • Then rest two lines are executed and it loops forever.
\$\endgroup\$
0
\$\begingroup\$

INTERCAL, 41 bytes

Based on answer by @unrelatedstring. If you don't care for errors, won't you guys golf off the program easily?

DOWRITEIN.1DOCOMEFROM.1(1)PLEASEREADOUT.1

Try it online!

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

Batch, 28 bytes

:1
@Echo(%1&Goto:%1
:0

uses input as output and script flow controller.

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

Add++, 7 bytes

+?
Dx,O

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ doesn't seem to work anymore but here is a 9 byte \$\endgroup\$
    – Hydrazer
    Jan 4, 2022 at 22:54
0
\$\begingroup\$

Pari/GP, 26 bytes

i=input;until(!i,print(i))

Try it online!

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

makina, 23 bytes

v>>P
>?EJ
U>PU
^0n<
;1<

Explanation

The first automaton starts in the top left, and immediately goes down and right into the ?, or if. The condition for the if is the E, or number input. Once input is given, the condition automaton jumps forwards and out of bounds, causing it to return its value. If that value is 0, or false, the first automaton turns left and goes into the top P, or print. The print spawns a new automaton going right, which jumps over the U-turn, goes left, into the n, or number. It reads the 0, turns up, does a U-turn, hits the semicolon (ending the number), and goes out of bounds, returning a 0 to the print. The first automaton then goes out of bounds and halts. However, if the value is 1, or true, the automaton turns right and proceeds directly into the n, goes left, reads the 1, and halts. Then, the first automaton goes out if the print, into the U-turn, making it go back to the arrow to the left of the print, starting the whole cycle again.

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

SMALL, 14 bytes

$->x{x=1?1!}0!

Ungolfed code:

$ -> x

{
    x = 1?
    1!
}

0!

We first read from stdin and store the input in x, with the following line.

$->x

We then enter an iteration, where we first compare if x is 1. If that's the case, we print 1. Since this check will never be false, this iteration will be infinite.

{
    x = 1?
    1!
}

If the condition in this iteration is false, the entire iteration stops and we go to the last line, which prints a single zero after which the program halts.

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

A0A0, 67 bytes

I0S1M2V0G0
G-1G-1G-1G-1
O0

A0A0
A0C3G1G1A0
A0O1A0
A0A1G-3G-3A0
G-3

The top line takes input, then adds one to this number and multiplies it by two. For input 0 we now have 2 and for input 1 we have 4. This is used as the offset for the goto instruction. If we jump by two we end up at line three which prints zero and halts. If we jump by four, we get to line five and get to an fininite loop.

A0  A0
A0  C3 G1  G1  A0
A0  O1 A0
A0  A1 G-3 G-3 A0
G-3

This infinite loop simply prints one (on the third line in the loop: O1).

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

Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes

?x(;

See the README to see how to run this

The ? could be replaced with a ! for the same effect.

?x(; # The program
?    # If
 x   # The input is truthy (i.e. 1)
  (; # Print the input forever
     # Otherwise print the condition (which was 0)
\$\endgroup\$
0
\$\begingroup\$

Python, 59 43 bytes

if input()=="1":
 while 1:print(1)
print(0)

-16 by Seggan

\$\endgroup\$
2
  • \$\begingroup\$ This can be significantly golfed: no need for explicit exit(), and the i variable can be inlined. \$\endgroup\$
    – Seggan
    Jul 26, 2022 at 18:32
  • \$\begingroup\$ Thanks, I didn't realize that it was inefficient. \$\endgroup\$
    – Eric Xue
    Jul 27, 2022 at 0:03
0
\$\begingroup\$

ArcPlus, 22 bytes

(: n (,))(@ (p n) (p n

Verbose version:

(set n (input))
(while (print n) (print n))
\$\endgroup\$
1
  • \$\begingroup\$ Link to language is dead \$\endgroup\$ Oct 1, 2020 at 22:26
0
\$\begingroup\$

nroff/troff, 27 bytes

Ties with user100411's 27 bytes answer. This version, however, does REALLY outputs 1's FOREVER for input 1, while previous version halts by stack overflow.

.de a
\\$1
.while \\$1 1
..

Try it online!

Usage

.a 0
.a 1
\$\endgroup\$
0
\$\begingroup\$

Thunno, \$ 6 \log_{256}(96) \approx \$ 5 bytes

(actually 4.94 bytes, but the leaderboard doesn't take floats)

!)[1ZK

(No ATO link since that's on an outdated version)

Explanation

!)[1ZK  # Implicit input
!       # Push `not input` (i.e., 1 if input == 0; 0 if input == 1)
 )      # Break if the top of the stack is truthy (i.e. input == 0)
        # Since the stack is filled with 0s at the start, 0 is implicitly output in this case
  [     # while True:
   1ZK  #  print 1
\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 2 bytes

Attempt This Online!

    # implicit input
(   # while TOS is not 0:
 ß  #  print without popping
    # implicit output
\$\endgroup\$
0
\$\begingroup\$

Desmoslang Assembly, 12 Bytes

7+2*IJTGE1TO

New contributor
Dadsdy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
0
\$\begingroup\$

(,) 140 Chars or 1.585/8*140 ~= 27.7 Bytes

((),((())))(,(,,(),,()),,,(()),()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(,,(()()))
New contributor
Dadsdy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\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\$
1
  • 4
    \$\begingroup\$ You could use x=input() and then x>0 \$\endgroup\$
    – Cyoce
    Sep 20, 2016 at 17:41
1
12 13 14 15
16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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