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

458 Answers 458

0
\$\begingroup\$

Pike, 94 bytes

Looks like C, but isn't C. Is interpreted. Is fast.

int main(){int x=(int)Stdio.stdin->gets();if(x!=0){for(;;){write("1");}}write("0");return 0;}

Ungolfed:

int main() {
  int x = (int)Stdio.stdin -> gets();
  if (x != 0) {
    for(;;) {
      write("1");
    }
  }
  write("0");
  return 0;
}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ I always want to pronounce Stdio as Studio :) Can you not write an integer to output? \$\endgroup\$ Jan 22, 2016 at 17:26
  • \$\begingroup\$ @ETHproductions before I actually learned C, I always assumed stdio.h was some sorta studio something because of Visual Studio... I dunno. To write a number to stdout as far as I can tell you need to use write("%d", x); because write wants a string or array(char) argument, which is even longer \$\endgroup\$
    – cat
    Jan 22, 2016 at 17:29
0
\$\begingroup\$

Boo, 34 bytes

def f(x):
 print x;while x:print x

Boo is a language inspired by Python and implemented in .NET. Its syntax is very similar to Python 2's.

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

CJam, 16 bytes

qi1={"1o_~"_~}&0
\$\endgroup\$
0
\$\begingroup\$

AnnieFlow, 6 bytes

010[!"

Here is the decompressed and more readable program:

010101101100000110111111

Breakdown:

010          there are two characters, 0 and 1
1            input is accepted, first symbol popped will be whatever it is
011          there are two stacks, 0 for output, 1 for input
011          1 push occurs when 0 is popped from 1
00           that push is symbol 0 on stack 0 (output 0)
0            pop from the output (halt) when 0 is popped from 1
0011         2 pushes occur when 1 is popped from 1
01           the first push is symbol 1 on stack 0
11           the second push is symbol 1 on stack 1 (replaces the symbol we popped)
1            pop from stack 1, which we just put 1 on, so we loop forever, outputting 1
11           loop forever doing nothing if the input is empty, won't matter

Note: under some interpretations of the language, the trailing 1s can be omitted, and the advanced interpreter does this automatically, also added 0 to the end if there are any trailing 1s. The actual decompression is

01010110110000011
\$\endgroup\$
1
  • 1
    \$\begingroup\$ With an interpreter to use the whole 8 bits/byte for golfing purposes, this could be an interesting golfing language. \$\endgroup\$
    – lirtosiast
    Feb 3, 2016 at 23:07
0
\$\begingroup\$

Pylons, 7 bytes.

izwp,1}

How it works:

i      # Get command line input.
z      # Skip the next instruction if the top of the stack is 0.
wp,1}  # While 1 is truthy, print the stack.
\$\endgroup\$
0
\$\begingroup\$

ForceLang, 52 bytes

set a io.readln()
label l
io.write a
if a="1"
goto l
\$\endgroup\$
0
\$\begingroup\$

Fission, 12 bytes

This is about the shortest I can do at the moment.

*;R?[   X!@J

Try it online

  R           # Create a atom heading right
   ?          # Set atom mass to input char 
    [         # Set direction right
        X     # Clone atom and sending one back
         !    # Print the character
          @   # Swap mass and energy on atom
           J  # Jump (48 for 0, 49 for 1)
*             # Kill program.  Landing spot for 0
 ;            # Kill atom.  Landing spot for 1

The length of this program is quite dependent on the landing spots for the Jump command. There is also a requirement for a bit of space between the [ direction setter and the X linear cloner. Otherwise an extra 0 will get printed. The input must be either 0 or 1 for this to work. The input is not validated.

Originally I was going to put up a 18 byte program which is more forgiving on invalid inputs.

R?@YI@0'L
O0'&[X'1
\$\endgroup\$
0
\$\begingroup\$

Javascript, 33 31 chars

while(alert(x=x||+prompt()),x);
\$\endgroup\$
1
  • \$\begingroup\$ I'm getting "ReferenceError: x is not defined". \$\endgroup\$
    – Adam Dally
    Apr 16, 2016 at 3:36
0
\$\begingroup\$

Common Lisp, 34 32 bytes

(if (= 1(read))(loop (print 1)))
\$\endgroup\$
2
  • \$\begingroup\$ This appears to be a duplicate of this. \$\endgroup\$
    – user45941
    Apr 11, 2016 at 18:18
  • \$\begingroup\$ Hmmm ... Are you printing the Zero? \$\endgroup\$
    – sergiol
    Jan 31, 2017 at 1:06
0
\$\begingroup\$

Turtlèd, 7 bytes

Turtlèd cannot output without halting, so the truth machine writes down infinite ones, like a turing machine's implementation might, onto the grid if input is 1.

!.{1r.}

Explanation:

!                  input into string variable

 .                 write current char of string var (by default the first char)
                   for a single char input, this will be the entire input

  {1  }            while the current char is 1
                   this loop is never run if input is zero, but if it is one, it will run
                   forever, as the last action of the loop writes 1 to the current cell

    r              move right, so that we constantly move right to write ones to infinite
                   cells

     .             write current char of string var (still by default the first char)
                   this is 1 if the loop was run at all. because the loop runs while the
                   current cell is one, this will cause the loop to rerun every time.

       [implicit]  output grid at end of program, program will only end if input isn't 1
\$\endgroup\$
0
\$\begingroup\$

LI, 4 bytes

?iRP

Explanation:

?i       if input is truthy (1):
  RP      Recurse the program with the printed (implied) input
         Else (0 is the only falsy value in LI) return (implied) input, 
              which is implicitly printed.
\$\endgroup\$
0
\$\begingroup\$

ABCR, 7 bytes

iAo7ox

ABCR is a stack-based programming language that allows a few simple operations on any of its three stacks and a single register.

Explanation:

i        Numerical input.  Places result in register.
 A       Queue register value to queue a.
  o      Output peek(a) as a number.
   7     while(register){
    o      output peek(a) again
     x   }
\$\endgroup\$
0
\$\begingroup\$

Dip, 6 bytes

?_1p?0

Body must be at least 30 characters; you entered 19.

\$\endgroup\$
1
  • \$\begingroup\$ Perhaps you should provide an explanation rather than a space filler... \$\endgroup\$
    – FlipTack
    Dec 22, 2016 at 13:23
0
\$\begingroup\$

Doxical, 11 bytes

[^]A{AdA}dA

First answer in Doxical!

Doxical is my new language, which is designed to be difficult to program in, and is grid-based. Also, there aren't any newlines in Doxical code, so every Doxical program is a one-liner.

Explanation (note that there are no comments in Doxical, this is just for clarification):

[^]         # Asks for user input, if input = 1, puts 1 into the Value,
            # If 0, puts 0 into the Value
   A        # Declares variable A as the Value
    {A  }   # While A > 0:
      dA    # Output A in decimal (1 forever)
         dA # Outside the while loop, output A in decimal (0 once)

Yes, "Value" is meant to be capitalised, see docs for more details.

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

BrainInt, 5 bytes

&^[!]

Explanation:

&     # Take user input, and store in current cell
 ^    # Boolean-ate current cell (nonzero -> 1, 0 -> 0)
  [ ] # Loop (while cell != 0)
   !  # Print current cell as integer
\$\endgroup\$
0
\$\begingroup\$

T-SQL, 22 bytes

s:print @ if @>0goto s

requires a variable with the name @, e.g.:

DECLARE @ BIT = 0

s:print @ if @>0goto s
\$\endgroup\$
0
\$\begingroup\$

PHP, 24 25 27 bytes

<?=do{echo$i;}while($i); // Also 24b
<?=$i;for(;$i&1;)echo$i; // 24b, added PHP's short echo, actually made it less

echo$i;for(;$i&1;)echo$i; // 25b
echo$i;while($i&1)echo$i; // 25b, based on 0/1 as truthy/falsy

for(;$i&1;){echo$i;}echo$i; //27b

This works by setting register_globals=on (which you shouldn't) and that going to the page with ?i=1 or ?i=0 in the url.

The logic is that the first echo will always output the input, and if it's one it'll loop until something gives in (because of & returning 1 (=truthy) for 1).

\$\endgroup\$
4
  • \$\begingroup\$ Does register_globals work with STDIN? \$\endgroup\$ Nov 10, 2015 at 19:19
  • \$\begingroup\$ I went for " or an acceptable alternative". I figured it's about the technique, not forcebly use STDIN. This is one of the very few 'keep the code shorter' tricks PHP can use, especially compared to the other languages :) \$\endgroup\$
    – Martijn
    Nov 11, 2015 at 8:27
  • \$\begingroup\$ I get 21 bytes with do{echo$i;}while($i); \$\endgroup\$
    – Xanderhall
    Dec 9, 2016 at 14:04
  • 1
    \$\begingroup\$ But not with the <?= in front of it. Added it nevertheless \$\endgroup\$
    – Martijn
    Dec 12, 2016 at 12:44
0
\$\begingroup\$

stacked, 10 bytes

[:out]loop

Assumes input is on TOS. Try it here!

Loops [:out] while TOS is truthy, repeating at least once. Surround with [] for a proper function.

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

tcl, 40

gets stdin r
puts $r
while \$r {puts $r}

demo

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

Deadfish i, 16 bytes

0<+I]
1<.
2<+.[2

As this language does not support input, you must replace I with either an empty string (=0) or + (=1). The program works on my interpreter, which may or may not work like the author of the language intended.

I'm not sure how to score this program. Currently the byte count is for 1-variant.

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

REXX, 33 bytes

pull n
do while n
  say n
  end
say n
\$\endgroup\$
0
\$\begingroup\$

Decimal, 32 bytes

81D301110D412D590D5111D91D30191D

Pretty simple. Explanation:

81D   ; builtin to read INT to stack
301   ; print
110D  ; push INT 0
412D  ; compare for equality, pop values used, push result
5     ; if truthy
90D   ;  exit
5     ; endif
111D  ; push INT 1
91D   ; declare jump 1
301   ; print
91D   ; exit

Try it online!

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

Noether, 5 bytes

0(IP)

This works very simply:

0 - Push 0 to stack
( - Pop value of stack and loop until top of stack equals popped value
I - Push user input to stack
P - Print top of stack
) - End loop

Unless you want your browser to freeze, I would advise against testing this online at https://beta-decay.github.io/noether

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

ArcPlus, 22 bytes [non-competing]

(: 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\$

Lean Mean Bean Machine, 18 bytes

 O
 i
 ?
 _
u $
  ~

Explanation:

 O    - Spawns a marble at program start
 i    - Fetch input and assign to marble's value
 ?    - If marble's value is truthy, spin right, else spin left
 _    - Move in direction of spin
u $   - u terminates marble and prints value, $ prints value
  ~   - Trampoline, move marble to top of field on same column

Yep, Mayube's at it again making another language that'll probably be abandoned in a week. This one's not at all golfy though, and inspired by this challenge

\$\endgroup\$
1
  • \$\begingroup\$ 2D languages generally aren't golfy. However, they're interesting to program in. \$\endgroup\$ Jul 17, 2017 at 20:47
0
\$\begingroup\$

Cubically, 29 28 bytes

$!7{%0&}U3D1R3L1F3B1U1D3(%1)

Try it online! (May not work for a little while after posting due to TIO's version) Explanation:

$                             read integer as input
 !7{...}                      if falsy
    %0                         print 0th face
      &                        exit
        U3D1R3L1F3B1U1D3      quickest way to get 1 onto a face
                        (..)  forever
                         %1    print the first face
\$\endgroup\$
1
  • \$\begingroup\$ L1D1L3 gets 1 onto face 0. \$\endgroup\$
    – TehPers
    Aug 5, 2017 at 11:04
0
\$\begingroup\$

Python 2, 50 bytes

a=bool(input())
print int(a)
while a: print int(a)

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You don't need to cast datatypes. 33 bytes \$\endgroup\$
    – Simon
    Sep 5, 2017 at 7:57
0
\$\begingroup\$

Assembly (as, x64, Linux), 128 bytes

.data
i:.byte 0
.text
mov $3,%eax
mov $0,%ebx
mov $i,%ecx
mov $1,%edx
int $128
l:mov $4,%eax
mov $1,%ebx
int $128
cmp $49,i
je l

Try it online!

Explanation

.data
i:.byte 0       ;Declare variable i with type byte

.text
mov $3,%eax
mov $0,%ebx
mov $i,%ecx
mov $1,%edx
int $128        ;Make system call read(eax=3) from stdin(ebx=0) with an address(ecx) and length in bytes(edx)

l:mov $4,%eax   ;Declare section/label l
mov $1,%ebx
int $128        ;make system call write(eax=4) to stdout(ebx=1). There is no need to reassign ecx or edx
cmp $49,i       ;compare the value at the address i to 49(ascii value of "1")
je l            ;jump to label l if equal
\$\endgroup\$
0
\$\begingroup\$

INTERCAL, 141 bytes

PLEASE WRITE IN .1
DO (1020) NEXT
DO (1) NEXT
DO COME FROM (3)
(3)DO READ OUT #1
(2)PLEASE RESUME .1
(1)DO (2) NEXT
DO READ OUT #0
DO GIVE UP

Try it online!

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

CMD, 30 bytes

:a
echo %1
if %1==1 (goto a)

Pretty straight-forward

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