145
\$\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
  • 3
    \$\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

368 Answers 368

0
\$\begingroup\$

Swift, 55 bytes, 54 bytes, 53 bytes

if readLine()=="1"{while 1>0{print(1)}}else{print(0)}

I tried to use ternary for a while but couldn't get it compiling. Maybe someone else will or it is just impossible. I'm open for tips or advice :)

\$\endgroup\$
  • \$\begingroup\$ instead of while(true) can you do while(1) or while(1>0)? \$\endgroup\$ – Cyoce Sep 5 '17 at 8:03
  • \$\begingroup\$ @Cyoce error: 'Int' is not convertible to 'Bool' \$\endgroup\$ – idrougge Nov 22 '17 at 11:52
  • \$\begingroup\$ @Simon You can shave off one byte by removing the parentheses after while. They serve no purpose in Swift. \$\endgroup\$ – idrougge Nov 22 '17 at 11:54
  • \$\begingroup\$ One byte shorter using ternary: readLine()=="1" ? {while 1>0{print(1)}} : {print(0)} \$\endgroup\$ – idrougge Nov 22 '17 at 12:06
  • \$\begingroup\$ @idrougge 'Expression resolves to an unused function' \$\endgroup\$ – Simon Nov 22 '17 at 12:24
0
\$\begingroup\$

Whispers, 34 bytes

> Input
>> Output 1
>> DoWhile 1 2

Try it online!

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

Pyt, 5 bytes

`Đƥłŕ

Explanation:

`  ł     (Do ... while top of stack is true)
 Đ       Duplicate top of stack
  ƥ      Print top of stack
    ŕ    Pop top of stack and discard

Try it online!

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

;#+, 28 bytes

;;;;;;;;~*~-(;~;;;;;;~)~p(p)

Try it online!

;;;;;;;;~*~-(;~;;;;;;~)~p(p)
;;;;;;;;                      set acc0 = 8
        ~*~                   set acc1 = input
           -(;        )       while(acc0--)
              ~;;;;;;~            acc1 -= 6
                              this leaves us with a `0` or `1` values for character input
                       ~p     print acc1
                         ( )  while(acc1)
                          p       print acc1
\$\endgroup\$
0
\$\begingroup\$

FALSE, 12 11 bytes

^'0-[$.$]$#
\$\endgroup\$
0
\$\begingroup\$

Draw, 21 bytes

start 0 1 start start

This is the version of the program where 1 is input. To change the input to 0, replace the 1 with a 0. The program where the 1 is there will produce an infinite line of marked squares towards y=+∞ starting at x=0, y=1; if the 1 was replaced, there will be only one marked square, at x=0, y=0.

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

Aheui, 33 bytes

방챵뱍벅나명희멍터벅벅

You can test it with jsaheui, or rpaheui.

How does it works?

// When input is 0
방챵뱍벅나명희멍터벅벅
ⓐⓑ    ⓖⓕⓔⓓⓒ

// When input is 1
방챵뱍벅나명희멍터벅벅
ⓐⓑⓓⓒⓔⓕ
   ⓖ
\$\endgroup\$
0
\$\begingroup\$

Kotlin Script, 41 bytes

readLine().let{while(it=="1")print("1")}

Pretty Printed:

readLine()
    .let{
        while(it=="1")
            print("1")
    }
\$\endgroup\$
0
\$\begingroup\$

Perl 6, 28 bytes

{.say;.say while $_}(+slurp)
\$\endgroup\$
0
\$\begingroup\$

Yabasic, 36 bytes

Another answer that takes input as integer, n and outputs to the console.

Input""n
If n Then Do?1Loop Else?0Fi

Try it online!

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

QUARK, 11 bytes

This is 6.75 bytes in QUARK's encoding, but that's not finished yet (no encoder), so I'll score this in UTF8 until then.

i‶{p}⟲

As QUARK became capable of doing a truth machine (implementation wise) less than a minute ago (from when I started writing this answer), it obviously needs an explanation, so here you go:

i Get input from the user (as a number)
 ‶ Pin the input to the stack (Pinning is QUARK's way of avoiding a million and one dupes, by simply making the value undeletable until you run the pin command on it again.)
  { Begin a block
   p Print a value off the stack. Because the input is pinned, it's not consumed.
    } End the block, and push it to the stack (when the program reaches this point)
     ⟲ Execute the block. If the top of the stack is not after the first execute 0, execute the block until it is. As the input is pinned, it will always be either 0 or 1. So the block either executes once, or infinitely.
\$\endgroup\$
0
\$\begingroup\$

Momema, 9 bytes

i0-8_Ii_I

Try it online! Requires the -i interpreter flag.

The provided Momema interpreter has a -i flag which enables interactive mode. In interactive mode, expressions can have holes, which evaluate to a value read from STDIN. Normally, this would just be equivalent to *-8, but it also allows holes to be named with a string of capital letters. When a named hole is evaluated, its value is cached, and when a hole with the same name is evaluated again it is reused. This is intended to be for debugging purposes, but it also means that we can refer to input without having to assign it.

Explanation:

                                                 #  i = input num
i   0   #  label i0: jump past label i0 (no-op)  #  do {
-8  _I  #            output num _I               #    print num i
i   _I  #  label i1: jump past label i(_I)       #  } while i
\$\endgroup\$
0
\$\begingroup\$

Quarterstaff, 12

49-?{49!}49! 

explanation

(value = 0 to start)

49 - add 49 to value

- - invert value (value = -49 now)

? - take a character of input (49 for "1", 48 for "0"), and add it to the value (value = 0 or -1 now)

{ - begin while not loop. will only be entered if input is 1 or starts with 1 (it should only start with 1 if it is 1).

49 - add 49 to value. value is now 49

! - print value, set value to 0.

} - end while not loop.

49 - add 49 to value (which was -1). value is now 48

! - print value, set value to 0 (not relevant to the program, but all ! do this)

it looks like it could be golfed by assigning 49 to something, but it would take 2 more bytes to assign it, then 2 more bytes to use it in the first part, then only byte saving of 2 for the other two occurences of 49

Previous version of Quarterstaff, 11

I removed %, so this isn't valid in the new version

?1%{49!}47!

? - input a character (49 for "1", 48 for "0") add to value

1 - add 1 (value is 50 or 49 now)

% - value = value %2 (0 if "1" was inputted, 1 if "0" was inputted)

{ - begin while not value loop

49 - add 49 to value

! - print value, value = 0

} - end while not value loop

47 - add 47 to value

! - print value, value = 0

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

TIS -n 1 1, 29 bytes

@0
ADD UP
L:MOV ACC ANY
JGZ L

Try it online!

ADD UP is a shorter form of MOV UP ACC, since the accumulator starts at zero, and we only ever see one value on the input (if that is not desired +4 bytes to add HCF after the last line).

MOV ACC ANY simply does the output. This line is also labelled L.

JGZ L jumps to L if the accumulator is greater than zero. (JNZ L, jump if non-zero, would work identically here.)

In the case where we have a zero for input, we do not jump, but instead wrap around to the first line (ADD UP). Since there is no more data to be had, the system goes quiescent.

In the case of a one, we will endlessly jump to L, outputting a 1 on every third cycle (writing to a neighbor actually takes two cycles in TIS).

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

Charm, 42 bytes

getline " 1 " eq put [ dup ] [ put ] while

Try it online!

You strangely can't cast to an integer in Charm, so I had to check for equality with 1 instead.

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

Ahead, 10 bytes

IsO@
~>1O~

Try it online!

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

ABAP, 61 bytes

Hardcoded VALUE 1 for variable i, replace with 0 to not trigger the infinite loop.

DATA x TYPE I VALUE 1.
WHILE i=1.
WRITE i.
ENDWHILE.
WRITE i.
\$\endgroup\$
0
\$\begingroup\$

2DFuck, 32 30 bytes

,.,.,.,.,.,.,.,.[!..!..!...!.]

Try it online!

Explanation:

,.,.,.,.,.,.,.,. Read and print a byte, accumulator is last bit = 0 or 1
[!..!..!...!.]   While the accumulator is 1, print 1
\$\endgroup\$
0
\$\begingroup\$

Python 2.7, 45 bytes

I just had the Eureka of this code:

x=int(raw_input())
print x
while x: print 1

I am proud of this one, though it may not look very impressive.

\$\endgroup\$
  • \$\begingroup\$ You don't need the indentation after if x==1:, also why not just do if x:? \$\endgroup\$ – Sriotchilism O'Zaic Jul 9 '18 at 20:24
  • \$\begingroup\$ @W W yeah I changed it. Also very late. \$\endgroup\$ – StealthyPanda Jul 23 '18 at 13:01
  • 1
    \$\begingroup\$ Change int(raw_input) to input() because Python 2's eval converts it automatically to int. \$\endgroup\$ – MilkyWay90 Jan 12 at 0:26
0
\$\begingroup\$

Assembly (nasm, x64, Linux), 119 bytes

mov eax,3
mov ebx,0
mov ecx,i
mov edx,1
int 80h
l:mov eax,4
mov ebx,1
int 80h
cmp byte [i],49
je l
section .data
i:db 0

Try it online!

I was surprised that, while there is a 128 byte submission in as, there isn't a nasm submission, despite it being shorter!

Literally a port of the as submission into nasm.

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

Clam, 11 bytes

p=a*rwa*pa*

Try it online!

Storing variables is a tad verbose in Clam...

Explanation

p=a*rwa*pa*
p            Print..
 =             Assignment..
  a*             Dictionary lookup 'myVar'
    r            Read next line of STDIN (automatically parsed to int if possible)
     w       While..
      a*       myVar is true
        pa*    Print myVar

Resulting JS code:

console.log(myVar = arguments[0]);
while(myVar) {
    console.log(myVar);
}
\$\endgroup\$
0
\$\begingroup\$

F# (.NET Core), 54 bytes

let x=stdin.Read()
while x=49 do printfn"1"
printfn"0"

Try it online!

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

IBM PC 8088 machine code, 14 12 bytes

TRUTH.COM:

a082 00b4 0ecd 103c 3174 f8c3

Ungolfed:

    MOV  AL, DS:[82H]
DISPLAY:
    MOV  AH, 0EH
    INT  10H
    CMP  AL, '1'
    JZ   DISPLAY
    RET

Output

A>DIR TRUTH
 Volume in drive A has no label
 Directory of  A:\

TRUTH    COM       12  01-01-80   12:01a
        1 File(s)    111776 bytes free

A>TRUTH.COM 0
0

A>TRUTH.COM 1
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111^C
(ended because Ctrl-C (^C) was hit)

Shouldn't ever crash or run out of memory since no memory is used. More likely it'll just burn a permanent screen full of 1's onto your IBM 5151 monochrome CRT monitor, so in a sense it will run forever.

Build and test it for yourself using DOS DEBUG.EXE!

A>DEBUG TRUTH.COM
a
mov al,[0082]
mov ah,0e
int 10
cmp al,31
jz 103
ret

rcx
c
w
q
\$\endgroup\$
0
\$\begingroup\$

bitch, 5 bytes

This infinitely outputs 1 for an input of 1 and outputs 0 once for an input of 0.

\>/;<
Try it online!

Explanation

\         Input of an integer (restricted by challenge to 0 or 1)
 >        Loop marker #1
  /       Output
   ;<     If not equal to 0, jump to loop marker #1
          (Implicit end of program)

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

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.