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

388 Answers 388

1
9 10 11 12
13
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
|improve this answer|||||
\$\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.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ You don't need the indentation after if x==1:, also why not just do if x:? \$\endgroup\$ – Ad Hoc Garf Hunter 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 '19 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.

|improve this answer|||||
\$\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);
}
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

F# (.NET Core), 54 bytes

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

Try it online!

|improve this answer|||||
\$\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
|improve this answer|||||
\$\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)

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Lua, 38 bytes

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

Try it online!

|improve this answer|||||
\$\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!

|improve this answer|||||
\$\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).

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ @JoKing implicit int type? That's good to know. \$\endgroup\$ – Benjamin Urquhart Mar 10 '19 at 4:23
  • \$\begingroup\$ You can even use main(i). \$\endgroup\$ – Jonathan Frech Mar 10 '19 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 '19 at 9:04
  • \$\begingroup\$ @JonathanFrech thanks. You can probably tell that I don't know C very well :) \$\endgroup\$ – Benjamin Urquhart Mar 10 '19 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.

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

C++ (gcc), 65 bytes

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

Try it online!

|improve this answer|||||
\$\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.
|improve this answer|||||
\$\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.

|improve this answer|||||
\$\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.

|improve this answer|||||
\$\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"
|improve this answer|||||
\$\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
|improve this answer|||||
\$\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).

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ This seems to be a duplicate of this answer. \$\endgroup\$ – Mr. Xcoder Aug 26 '19 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.

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 32 bytes

do{alert(x=x||prompt())}while(x)
|improve this answer|||||
\$\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.

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Wren, 55 bytes

Fn.new{|x|
while(x){
System.print(x)
if(x==0)Fn.x()
}
}

Try it online!

Explanation

Fn.new{|x|      // As usual, new anonymous function x
                // Newline as we are entering statements, not an expression
while(x){       // While the input x is true:
                // (Everything other than false, the null string, and the
                // empty list is true)
System.print(x) // Output x to the console with a newline
if(x==0)Fn.x()  // If the input is 0 then exit the program
}
}
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Comp, 6 or 8 bytes

The first golfing language (sort of :) ) from 2020!

;{^&}&

That could be a mistake. An alternative program is:

;{^£}£

Explanation

;      Take an input from the console as an integer
 {^£}  While that's nonzero, duplicate & print
     £ If that's zero, directly print
|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

AWK, 17 bytes

{while($0)print}1

Try it online!

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

RAKIAC machine language, 6 bytes (34 real for asm)

00000100
00000011
00110100
00100001
00000001
00000010

Representing the assembly:

in
s: out
jez v
jmp s
v: hlt
end

Tried out one of my things for fun (definitely not made for golf).

|improve this answer|||||
\$\endgroup\$
0
\$\begingroup\$

Turing Machine Code, 19 29 19 bytes

0 0 * * h
0 * 1 r 0

Try it online!

Saved 10 bytes thanks to @Laikoni

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ This is doable with just two rules: 0 0 * * h and 0 * 1 r 0. \$\endgroup\$ – Laikoni Feb 26 at 12:54
-1
\$\begingroup\$

Ruby, 22 bytes

->(n){n==0?0:loop{p1}}
|improve this answer|||||
\$\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.

|improve this answer|||||
\$\endgroup\$
  • 3
    \$\begingroup\$ You could use x=input() and then x>0 \$\endgroup\$ – Cyoce Sep 20 '16 at 17:41
1
9 10 11 12
13

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.