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

377 Answers 377

2
\$\begingroup\$

Python 2, 50 39 bytes

Don't know why nobody mentioned I could just write input()

i=input()
while(int(i)):print 1
print 0

Very simple, if the input is 1, will continuously print 1 and cannot reach the print 0. If it is 0, the while will never fire.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can save a few bytes by using stdin instead of command line args. \$\endgroup\$ – pppery Aug 6 '17 at 23:04
  • \$\begingroup\$ 29 bytes, you don't need to cast the input to an int because the input function in Python 2 does eval on the input before returning. You also don't need parentheses around the input call. \$\endgroup\$ – LyricLy Sep 29 '17 at 22:02
  • \$\begingroup\$ Oh, actually... This code doesn't even work. Theoretically, it would work if infinite 1's were given as input, but that doesn't meet the spec. Since while is calling the input function every time, it will just print one 1 and then reach the end of the input and error. Your earlier solution with command line args did work, or you can assign the input to a variable before looping. \$\endgroup\$ – LyricLy Sep 29 '17 at 22:13
  • \$\begingroup\$ @LyricLy yeah, I tried that once. Thanks! \$\endgroup\$ – Stan Strum Sep 30 '17 at 19:14
2
\$\begingroup\$

JavaScript, 26 bytes - Variation of Solomon Ucko's answer

I find it weird how I can't comment, but I can edit his answer...

for(;alert(i=prompt())|i;)
\$\endgroup\$
2
\$\begingroup\$

Forked, 22 21 bytes

-1 thanks to BMO

v >%&
$ |
>-:
  |
 %<

The IP path looks like this if the inputted integer is truthy:

v
|
>-v
  |
 %<

Upon hitting % (print as integer), it goes off the edge of the playing field and wraps around, running >% infinitely.

It takes this path if the inputted integer is falsy:

v >%&
| |
>-^

It prints % 0 and then exits &.

\$\endgroup\$
2
\$\begingroup\$

ORK, 395 bytes

There is such a thing as a m.
A m can p a word.

When a m is to p a word:
I have a scribe called W.
W is to write the word.
I have a linguist called C.
C's first operand is the word.
C's second operand is "1".
C is to compare.
If C says it's equal then I am to loop.

When this program starts:
I have a inputter called R.
I have a word called N.
R is to read N.
I have a m called M.
M is to p N.

Try it online!


Here's the ungolfed version, which is not a whole lot different:

There is such a thing as a truth machine.
A truth machine can process a word.

When a truth machine is to process a word:
There is a scribe called Keymaker.
Keymaker is to write the word.
There is a linguist called Chomsky.
Chomsky's first operand is the word.
Chomsky's second operand is "1".
Chomsky is to compare.
If Chomsky says it's equal then I am to loop.

When this program starts:
I have an inputter called Dave.
I have a word called Input.
Dave is to read Input.
I have a truth machine called Hal.
Hal is to process Input.

The first paragraph defines a truth machine class with one member function, process, which takes a string (i.e. word).

The second paragraph defines process: write the string out, and then compare it against "1". If it's equal, loop.

The third paragraph defines our main function: read a string in, instantiate a truth machine, and have the machine process the string.

Simple, really.

\$\endgroup\$
2
\$\begingroup\$

R, 29 27 bytes

2 bytes brilliantly saved by @Giuseppe

x=scan();while({cat(x);x})1
\$\endgroup\$
  • \$\begingroup\$ the other R solution isn't valid, but there's another two bytes you can squeeze out of this! click here to spoil it \$\endgroup\$ – Giuseppe Mar 3 '18 at 15:38
  • \$\begingroup\$ @Giuseppe that is great. \$\endgroup\$ – MickyT Mar 3 '18 at 19:51
2
\$\begingroup\$

Stax, 5 4 3 bytes

Crossed out 4 is still 4 ;(

wQc

Try it at staxlang.xyz!

 w      Until popping results in a falsy value:
  Q       Peek and print with a newline.
   c      Copy the value atop the stack.

I'm loving this new language.

Thanks to @Weijun Zhou for reminding me of implicit input.

\$\endgroup\$
  • \$\begingroup\$ I am glad to find another user of Stax writing impressive answers. Maybe you should check out the chat as well although there are not much to see at the moment. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 20:57
  • \$\begingroup\$ You don't need the comma at the beginning. There is implicit input. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 21:03
  • \$\begingroup\$ Also I suggest you use this link: staxlang.xyz/#c=wQc&i=0%0A1&a=1&m=2. It automatically runs your program. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 21:14
  • \$\begingroup\$ @WeijunZhou Whoops, thanks! \$\endgroup\$ – Khuldraeseth na'Barya Mar 3 '18 at 21:14
2
\$\begingroup\$

Reflections, 26 bytes

  _:#_: _<
/#_v     /
\: /

Test it!

Explanation:

The _ at position (2|0) reads a line from input, : doubles the first character. Then, # redefines zero and _ at (1|0) prints that character. : doubles the first character again, _ at (4|0) converts a digit to a number. < tests this number, if it's 0, the IP is directed upwards (out of the program). Else it's directed downwards, then left by the /, and down again by the v, left by the /. The : doubles the character again. Then, the \ reflects the IP upwards and the / right again, where # redefines zero and the _ at (1|0) prints the character. The v then directs it down into the loop again.

\$\endgroup\$
2
\$\begingroup\$

Python 2, 59 51 49 33 bytes

i=input()
while i:print 1
print 0

Explanation:

input()             # take input from STDIN
while i:print 1     # print 1 if the argument is anything other than 0... input() evaluates the string and returns a value
print 0             # print 0 and exit if input() returns 0

EDIT: Saved 8 bytes thanks to @EsolangingFruit

EDIT 2: Coupla more bytes thanks to @HyperNeutrino

EDIT 3: Saved 16 bytes thanks to @HyperNeurtrino

\$\endgroup\$
  • 1
    \$\begingroup\$ You don't need to have str(1), you can just do print"1", etc. \$\endgroup\$ – Esolanging Fruit Mar 6 '18 at 2:57
  • \$\begingroup\$ remove the space between print and ' (this is Esolanging Fruit's suggestion but you added an extra space so credit them instead for 8 bytes) \$\endgroup\$ – HyperNeutrino Mar 6 '18 at 3:28
  • \$\begingroup\$ also, don't take arguments, use input. k=input()>"0" and then while k:print 1 and then print 0 (note that you don't even need to do print"1", just do print 1 \$\endgroup\$ – HyperNeutrino Mar 6 '18 at 3:29
  • \$\begingroup\$ @HyperNeutrino Thanks. Fixed the first thing... still looking at input() it's not doing what I expect it to. \$\endgroup\$ – Allen Fisher Mar 6 '18 at 4:42
  • \$\begingroup\$ @HyperNeutrino This is Python 2, so input() returns an evaluated value instead of a string. This means that input() already returns the number. \$\endgroup\$ – Esolanging Fruit Mar 6 '18 at 5:06
2
\$\begingroup\$

MATL, 4 bytes

`GtD

Relevant MATL features *

To explain the code, the following MATL features need to be presented first.

  • ` ...] is a "do ...while" loop. The top of the stack is consumed at the end of each iteration, and used to decide whether to go on with a new iteration or not. The last ] can be omitted if it's at the end of the program (loops are implicitly closed).
  • G works as follows:
    • When there has been no user-input it does nothing;
    • When there has been one user-input it pushes it onto the stack
    • When there has been more than one user-input it takes a numeric argrument and pushes one of those user-inputs onto the stack
  • t by default duplicates the top element of the stack
  • D by default displays the top element of the stack, and consumes it.
  • If a function requires more inputs than currently are in the stack, user-input is implicitly triggered. The entered elements are placed below the current bottom of the stack.

Code explanation

` enters the loop. At the first iteration, G does nothing. t implicitly asks for user input and duplicates it. D displays and consumes the duplicate, leaving the original input on the stack. If this input is 0 the loop is exited and the program finishes (a single 0 has been displayed). If the input is 1, control goes to the beginning of the loop again. Now G pastes the input, t duplicates it, D displays and consumes that duplicate, and again there's a 1 to be used as loop condition, so the loop begins again, indefinitely (an infinite number of 1 is displayed).


* at the time of writing. The behaviour of G has changed since then: G now triggers implicit input when there has been no user-input yet. However, this doesn't affect the code, which works the same. The only difference is that in the first iteration the implicit input is now triggered by G, not by t.

\$\endgroup\$
2
\$\begingroup\$

Pepe, 15 bytes

REeErEErReEEree

Try it online!

Explanation:

REeErEErReEEree  # Full program
REeE             # Take input as number
    rEE          # Create label 0
       rReEE     # Output number -r (preserve)
            ree  # Goto label 0 if [input] != 0
\$\endgroup\$
2
\$\begingroup\$

Self-modifying Brainfuck, 30 19 bytes

Similar method to my BF answer. Input and print, subtract the 0 (the source's last byte) from the input, so cell is 0 or 1. Loop printing if input cell is 1. Tested on my Python interpreter.

,.<[->-<]>[<<.>>]10

You can also run it on TIO.

\$\endgroup\$
2
\$\begingroup\$

Flobnar, 10 bytes

<1._
|@&
0

Try it online!

\$\endgroup\$
2
\$\begingroup\$

AlgiX with -x, 3 bytes

[.]

Explanation

AlgiX takes each character of input (converts it to charcode if it's not a digit) and runs the entire code for each value, initializing the accumulator to that value each run.

In this case, there's only 1 input, a 1 or a 0, so the code runs once.

[.] - Implicit a = input
[   - If a == 0, skip to ]
 .  - Print value of a
  ] - If a != 0, jump back to [
    - Implicit output value of a

Normally, the implicit output after each run would output a as a character, however the -x flag overrides that and outputs its value instead.

\$\endgroup\$
2
\$\begingroup\$

VSL, 36 32 bytes

fn main(){do{print(i)}while i>0}

This is probably familiar to anyone who knows any C-esque language but this takes input using a global variable i.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Befunge, 4 bytes

&:.%

Try it online!

Please note: this answer is no longer valid with this particular interpreter. At the time of writing, the interpreter used had a quirk where trying to read more integers when there weren’t any would return the last integer. I believe that this was “fixed” in some interpreter update. (Thanks to @osuka_ for realizing that this answer no longer works)

Explanation:

&       Take number input
 :.     Duplicate and print input
   %    Mods the second from-the-top with the top number in the stack
        This means that if the top is 1, it will yield 0 % 1 = 0,
        But if it is a 0, it errors out and stops execution because you are
        trying to divide by 0

&       The program wraps back around if it didn't error, and the & takes
        the last number in the input if it has already taken them all, yielding
        the original 1 or 0

Coincidentally, this doesn't also work for /, because it strangely asks you what you want the answer to be.

\$\endgroup\$
  • 1
    \$\begingroup\$ The modulo trick is really clever. I love it. \$\endgroup\$ – IQuick 143 Apr 30 at 14:15
  • 1
    \$\begingroup\$ This doesn't work - it prints -1 instead of 1 after the first time. \$\endgroup\$ – osuka_ Aug 26 at 18:56
  • \$\begingroup\$ @osuka_ I think it’s due to the interpreter being updated, unfortunately. I remember it used to be that reading an end of feed with & would give the last integer again (which would make this print 1). I think they changed it so it gives -1 on an EOF instead. Thanks for letting me know \$\endgroup\$ – MildlyMilquetoast Aug 26 at 19:19
  • 1
    \$\begingroup\$ @MildlyMilquetoast No worries - The reason I stumbled upon this is that I was looking for other befunge answers, to see if anyone had already posted one identical (or very similar) to one I just wrote. I love the mod trick! \$\endgroup\$ – osuka_ Aug 26 at 19:30
  • \$\begingroup\$ This can be fixed by adding two !s after the & \$\endgroup\$ – Jo King Aug 27 at 3:48
2
\$\begingroup\$

Verbosity v2, 290 bytes

IncludeTypePackage<OutputSystem>
IncludeTypePackage<InputSystem>
IncludeStructurePackage<Loops>
input=InputSystem:NewInput<DEFAULT>
outpu=OutputSystem:NewOutput<DEFAULT>
condi=InputSystem:ReadEvaluatedLineOfInput<input>
Loops:ConstructLoop<Do;condi>[OutputSystem:DisplayAsText<outpu;condi>]

Try it online!

First non-trivial Verbosity v2 answer! Although how it works is very trivial, as you can see from the ungolfed version:

IncludeTypePackage<OutputSystem>
IncludeTypePackage<InputSystem>
IncludeStructurePackage<Loops>

input  = InputSystem:NewInput<DEFAULT>
output = OutputSystem:NewOutput<DEFAULT>

condition = InputSystem:ReadEvaluatedLineOfInput<input>

Loops:ConstructLoop<Do; condition> [
	OutputSystem:DisplayAsText<output; condition>
]

Try it online!

Simply enter a do...while loop, which prints the input at least once, then terminates if it's falsey (i.e. 0).

\$\endgroup\$
1
\$\begingroup\$

Ruby, 32 30 bytes

p gets.to_i<1?0:loop{p 1};exit
\$\endgroup\$
1
\$\begingroup\$

APL, 9 bytes

{⎕←⍵:∇⍵}⎕

Explanation:

          ⎕  ⍝ read a number from the keyboard
{⎕←⍵:   }    ⍝ output it, and if it is true:
      ∇⍵     ⍝ call the function again with that input
\$\endgroup\$
1
\$\begingroup\$

Pip, 5 bytes

WaPaa

In pseudocode:

while(a)
    print(a)
autoprint(a)

a is the first command-line argument. (The OP commented on the sandbox post that this was an acceptable way to take input, even though Pip is capable of taking input from stdin.)

\$\endgroup\$
  • \$\begingroup\$ WaPaa. I love these weird types of languages because when you put them into TTS programs they have a conniption. \$\endgroup\$ – Cyoce Dec 16 '15 at 18:29
1
\$\begingroup\$

Stack, 67 bytes

{ '1' print a call } `a set '' input num 1 = a { '0' print } ifelse

Run by placing the stack folder into your python lib folder, and running py -3 -m stack.cli truth.stack

\$\endgroup\$
1
\$\begingroup\$

3var, 6 bytes

">|[w]

Each 0 or 1 is followed by a newline. I've never actually used 3var's loop features before, so this is a first for me.

Explanation

"         Read input into R
 >        Copy R into A
  |[ ]    Do while A > B...
    w     Output R
\$\endgroup\$
1
\$\begingroup\$

Browser LiveScript, 54 bytes

switch prompt!
|'0'=>alert 0
|'1'=>while true
 alert 1

I believe I can use prompt and alert instead of STDIN and STDOUT with browser languages, is that correct?

\$\endgroup\$
  • \$\begingroup\$ Yes, you are correct. \$\endgroup\$ – Conor O'Brien Jan 16 '16 at 18:17
1
\$\begingroup\$

pb, 21 bytes

^t[B]v<w[B!48]{>b[T]}

There is currently only one pb interpreter. It's called pbi and it's hot garbage. I wrote it, and I have 0 other experience writing that kind of program. The pb variables are global variables in pbi's source code, loops are implemented recursively (the tokenizer turns the entire code of the loop into a single token, then when it's reached that token is sent back into the tokenizer and is executed until the condition becomes false), the function to evaluate an expression is def expression(e): return eval(e, globals())... overall it manages to do basically nothing right and I'm probably going to rewrite it.

I bring this up because pbi in its current state only outputs anything when the program terminates, so a 1 input makes it look like it does nothing forever. Here are the reasons why I believe this answer is valid anyway:

  • The canvas is being written to, which is how output works in pb. If the loop were to eventually terminate somehow, a lot of 1s would be outputted at once.
  • There is a way to watch program execution in pbi. It's intended for debugging and it's about as horrible as the rest of the interpreter, but the flag -d= followed by a number will print the canvas and pause execution for that many milliseconds after each tick.

How it works

^        # Move the brush to Y=-1, where input lives
t[B]     # Save the value at (0, -1) to T
v<       # Go to (-1, 0)
w[B!48]{ # While the space under the brush doesn't have the value 48 ('0'):
           # (this loop is guaranteed to be entered at least once)
  >        # Increase the brush's X coordinate by 1
  b[T]     # Save the value in T to the brush's current coordinates
}        # If the input was '0', the space under the brush has the value 48 and the loop is
         # terminated. Otherwise, it repeats indefinitely.
\$\endgroup\$
1
\$\begingroup\$

C++, 83 77 76 bytes

#include<iostream>int main(){int n;std::cin>>n;do{std::cout<<n;}while(n);}

Ungolfed:

#include <iostream>     // Needed for IO
int main()              // Necessary for any C++ program
{
    int n;              // Declare integer variable
    std::cin >> n;      // Retrieve input from STDIN
    do                  // Perform the following at least once
    {
        std::cout << n; // Output number, either 0 or 1
    } while(n);         // Continue doing so if number wasn't 0
}

Thanks to @feersum for letting me know that input can only be 0 or 1 I saved 6 bytes.
Thanks to @Alex A for saving another byte by removing a space

\$\endgroup\$
  • \$\begingroup\$ n is already 0 or 1 after you read it. n=!!n does nothing at all! \$\endgroup\$ – feersum Nov 4 '15 at 2:15
  • \$\begingroup\$ Oh so I needn't account for situations where STDIN contains numbers that aren't 0 or 1? \$\endgroup\$ – Tas Nov 4 '15 at 2:18
  • \$\begingroup\$ 0 and 1 are the only possible inputs. \$\endgroup\$ – feersum Nov 4 '15 at 2:22
  • \$\begingroup\$ Sweet! Thanks for letting me know! I will update my answer. \$\endgroup\$ – Tas Nov 4 '15 at 2:22
  • \$\begingroup\$ You can remove the space before <iostream>, saving 1 byte. \$\endgroup\$ – Alex A. Nov 4 '15 at 3:04
1
\$\begingroup\$

???, 37 bytes

?!";.;.--,'",'";,-,,,,,'";...'";!-'"

This is a simple translation of mbomb's Brainfuck solution.

\$\endgroup\$
1
\$\begingroup\$

SWI-Prolog, 45 bytes

m(X):-put(X),(X=48,halt;m(X)).
:-get(X),m(X).

The put and get predicates work with character codes, so we need to test against 48 for the 0 case. If that succeeds, halt; if it fails, try m(X) recursively instead.

To run from Linux command-line, put the code in a file and execute swipl -qs truth.pro. (The q is optional; it suppresses extra output from the interpreter.) Or, try it here.

\$\endgroup\$
  • \$\begingroup\$ I guess you can remove the halt, since directives are only executed once (next() and close()). But the link somehow doesn't work, it gives an error. \$\endgroup\$ – Transfinite Numbers Nov 7 '15 at 10:25
  • \$\begingroup\$ On the other hand to be ISO Prolog compliant, you would need initialization/1 swi-prolog.org/pldoc/man?predicate=initialization/1, since arbitrary directives are not allowed. The above would run in GNU Prolog. \$\endgroup\$ – Transfinite Numbers Nov 7 '15 at 10:30
  • \$\begingroup\$ @j4nbur53 The reason why I included halt is that with swipl on Ubuntu, not including it drops to a user prompt after the above code executes. I don't know what the exact policy on that is, but it seems like extraneous output that can be avoided, so I figured I'd better avoid it. \$\endgroup\$ – DLosc Nov 7 '15 at 23:04
1
\$\begingroup\$

Batch, 31 bytes

@IF 0%1==01 echo 1&%0 1
@echo 0

On my machine, running <script name> 1 twice from the command prompt caused CMD to crash. The first time it stopped after printing a lot of lines with 1s on it. (Presumably because of CMD running out of memory.)

Explanation

@ – This tells CMD not to print the commands on this line. (Output will still be printed.)
%1 – This will be substituted with the first argument given.
%0 – This will be substituted with the script name.

The first line will output 1s and then launch the script itself with an argument 1 if the script was called with the argument 1. Otherwise, the condition evaluates to false and the script will proceed to the second line. It will then output 0 and exit.

\$\endgroup\$
1
\$\begingroup\$

Math++, 11 bytes

?>a
a
2*a>$

Explanation:

1:Set a to a number from the input
2:Print a (the designator ">out" is implied if none is specified)
3:If a is 1, go to 2; if a is 0, exit
\$\endgroup\$
  • \$\begingroup\$ Could you add an explanation? \$\endgroup\$ – Addison Crump Nov 4 '15 at 12:45
  • \$\begingroup\$ @VoteToClose Done \$\endgroup\$ – SuperJedi224 Nov 4 '15 at 13:49
1
\$\begingroup\$

Loader, 30 bytes

run from m.ldr (or replace the m in the last line with the name of the file)

~B:set B =@IN
print B
B:load m

Theoretically infinite, in practice will result in Error: Stack Overflow in the reference implementation.

With comments:

~B:set B =@IN !!If B is zero (the default for uninitialized variables), set B to a number from the input
print B !!Exactly what it says on the tin
B:load m !!If B is nonzero, load a separate instance of this module on a copy of the current memory space
\$\endgroup\$
1
\$\begingroup\$

TML, 14 bytes

d={1 or 0}/0000-1111/

e.g

d=1/0000-1111/

or

d=0/0000-1111/

Finally I was able to use my language for something :) Since TML hasn't got an IO support (yet), the value must be hardcoded in the tape, but it should work as intended! If the value is 0 it halts (goes to card 0), else it will print an infinite string of 1s

Otherwise I have a 2 cards solution using the default tape:

{0 or 1}/0000-1112/0112-1112/
\$\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.