161
\$\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
  • \$\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\$ Nov 3 '15 at 17:38
  • 4
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Nov 6 '15 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Nov 10 '15 at 1:13

436 Answers 436

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

Pinecone, 41 bytes

n:"".input;n="1"?(tru@print:1)|(print:0)
\$\endgroup\$
0
\$\begingroup\$

CSASM v2.3.1, 54 bytes

func main:
in ""
conv i32
.lbl a
dup
dup
print
brtrue a
ret
end

Explanation:

func main:
    ; Get the input and convert it to an integer
    in ""
    conv i32

    .lbl a
        ; Duplicate the input twice
        ; Both the "print" and "brtrue" instructions pop a value from the stack
        ;   so this is necessary to keep a 1 on the stack when looping
        dup
        dup
        print

        ; Truthy values are a non-zero integer or a non-null object
        brtrue a
    ret
end
\$\endgroup\$
0
\$\begingroup\$

CASL II, 72 bytes.

Tested here.

A START
 IN B,1
D OUT B,1
 LAD GR1,48
 XOR GR1,B
 JNZ D
 RET
B DS 1
 END

If you are familiar with assembly languages, you would get it well. It uses standard i/o. It uses ASCII-compatible encoding.

\$\endgroup\$
2
  • \$\begingroup\$ It's stupid that START requires a label. \$\endgroup\$ May 5 at 5:20
  • \$\begingroup\$ Also it's buggy because 1 in IN B,1 and OUT B,1 is an address rather than a literal; maybe buffer overflow may occur when assembled. However, wherever the assembled code starts from, it seemed that those two macros are assembled using LAD command: actually not problem, at least on this emulator. \$\endgroup\$ May 6 at 7:09
0
\$\begingroup\$

Pxem, 0 bytes (content) + 13 bytes (filename).

Filename is:

._.c.n.w1.o.a

Try it online!

As verbose pseudocode

push numeircal integer input
dup
unless empty: printf "%d", $(pop)
while one of
  1. empty
  2. $(pop) != 0
do
  push "1", a character
  unless empty: printf "%c", $(pop)
done
\$\endgroup\$
0
\$\begingroup\$

Duocentehexaquinquagesimal, 2 bytes

Try it online! Takes input as a character, and outputs in unary using characters.

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

Subleq (8-bit), 15 bytes

-1 15   3
15 16   6
15 -1 -48
16  8  -1
15  8   6

Explanation

  • 0: -1 15 3 Input character to 15:, goto 3
  • 3: 15 16 6 16: = 16: - 15: (16: = -15), goto 6
  • 6: 15 -1 -48 Output 15: (-48 is unused in instruction and used for memory)
  • 9: 16 8 -1 8: = 8: - 16: , if 8: <= 0 exit; exit for all characters "0" and before
  • 12: 15 8 6 8: = 8: - 15: (back to -48), if 8: <= 0 goto 6
\$\endgroup\$
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\$

Dis, 49 bytes.

}{*|*^__________!||_^_____________*{___^___****!*

Usage

  • Input from STDIN, as an ASCII number character.
  • Output to STDOUT, in ASCII.

With comments

(
0: }{*|*^
'*'+1: ****!* 

'*'+1: * changed to 48-42or49-42 by |:
   12 10t - 11 20t is 01 20t is 15
   12 11t - 11 20t is 01 21t is 16 

'*'+2: * for * command 

'*'+1: 15or16 for ^ 

15+1: ! reaches when zero
16+1: ||^ reaches when one 

obtw '*'+3: * and '*'+4: * are for | to have the register A have 49 again 

'*'+5: ! for ^ 

After that '*'+4: '1' BUT whatever 

'!'+1: *{___^ repeatedly output one 

* 42 ! 33 

) 

(
0123456789 0123456789 0123456789 0123456789
)
}{*|*^____ ______!||_ ^_________ ____*{___^
(
0123456789 0123456789 0123456789 0123456789
)
___****!*

Try with 0!

Try with 1!

\$\endgroup\$
1
  • \$\begingroup\$ I think I can golf more. \$\endgroup\$ Jun 23 at 10:03
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 at 22:32
  • 1
    \$\begingroup\$ No, while 1: is not allowed, unfortunately. However, the space can be removed. Thanks for the tip. \$\endgroup\$
    – NimUser
    Jun 28 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 at 3:37
  • \$\begingroup\$ Oh, right. Sorry, stupid of me. \$\endgroup\$
    – NimUser
    Jun 28 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\$ Aug 19 at 2:52
  • \$\begingroup\$ How the hell can I do so? \$\endgroup\$ Aug 19 at 12:13
-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
  • 3
    \$\begingroup\$ You could use x=input() and then x>0 \$\endgroup\$
    – Cyoce
    Sep 20 '16 at 17:41
1
11 12 13 14
15

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.