178
\$\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\$
19
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ Commented Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Commented Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Commented Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Commented 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\$ Commented Apr 26, 2020 at 1:42

509 Answers 509

1
6 7
8
9 10
17
2
\$\begingroup\$

Grok, 10 bytes

:}1j z}zhq 

Explanation:

:} # If input is 0, goes down and to the left, outputs 0, z} q wraps to the right, and terminates. :}1j # If input is non-zero, goes to the right, pushes 1, }zh prints 1, and loops indefinitely. 
\$\endgroup\$
2
\$\begingroup\$

Stax, 4 bytes

Wq|c 

Run and debug it

W - loop over rest of program forever q - print without popping, with no newline |c - exit if value at the top of stack is truthy without popping 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the site, and nice first answer! \$\endgroup\$ Commented May 21, 2021 at 21:37
2
\$\begingroup\$

2D Deadfish, 7 bytes

(o^)>o< 

It is a new 2D esolang based on Deadfish~ I made recently. Read more on it in the link in header.

Explanation

IP starts at the beginning with direction right. Statements inside parentheses is only executed if accumulator is 0. And input is set to the accumulator, or else 0.

So if you give input 0,

  • Parentheses block will start
  • o will output accumulator (which is 0)
  • ^ will change direction to up
  • It will eventually hit EOF token
  • And terminate soon!

And for input 1,

  • Skip the parentheses and jump to >
  • > changes direction to right (It keeps moving right)
  • o outputs accumulator (which is 1)
  • < changes direction to left (back)
  • o outputs 1 again
  • > changes direction to right
  • IP dances and repeats outputting 1

How to run it?

No online interpreter for now. but coming soon.

Until then clone the repo, and run interpreter.py. It will prompt you for the program first. When done typing program, hit CTRL+D (linux) or CTRL+Z (windows). And provide your input (if you don't want to give keep it blank) and hit enter. The program will start to run.

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

Piet, 12 codels

Codel size 16:

3x4 codel piet truth machine

Instructions:

INN DUP (start) DUP OUTN PTR (back to start if 1; continue if 0) POP 

It has the following behavior for other values:

  • if n % 4 == 1, print n forever
  • else, print n once and terminate

if n % 4 == 2, there will be a stack underflow error, as the code path is as follows:

INN DUP DUP OUTN PTR SWITCH (empties the stack) PTR (error) POP (error) 
\$\endgroup\$
2
\$\begingroup\$

Arduino, 133 129 117 bytes

Thanks to @tail spark rabbit ear for shaving off 12 bytes!

#define S Serial int x=0;void setup(){S.begin(300);}void loop(){S.available()&&S.print(x=S.read()-48);x&&S.print(1);} 

Arduino is basically C++, but with this bit implied:

int main() { setup(); while (true) { loop(); } return 0; // to make the compiler happy, I guess } 

The setup() and loop() functions must be implemented.
Explanation:

#define S Serial /* macro to make referencing the Serial monitor shorter */ int x = 0; // must either be global, or declared `static` inside `loop()` void setup() { S.begin(300); // The argument to Serial.begin() is the baud rate // 300 is the slowest supported option, but therefore takes the fewest bytes } void loop() { S.available() && // Serial.available() returns truthy when there are unread bytes from the serial input // Using && as a shortcut for an if statement (like minified JS) S.print( x = S.read() - 48 ); // Serial.read() dequeues the next byte from the input // 48 is ASCII '0' // Serial.print() converts 0 back to "0"; Serial.write() wouldn't x && S.print(1); } 

As loop() is called indefinitely, it's impossible to terminate, so inputting "0" settles into a loop that prints nothing until something else is input.

Original:

int x=0;void setup(){Serial.begin(300);}void loop(){if(Serial.available()){x=Serial.read()-48;Serial.print(x);}if(x)Serial.print(1);} 
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! Would it be possible for you to provide either a link to the language, or a link to a testing environment, so that others can run your code? \$\endgroup\$ Commented Aug 13, 2021 at 2:27
  • 1
    \$\begingroup\$ @Dudecoinheringaahing Unfortunately no. In order to run Arduino code you have to deploy it to a physical Arduino board. \$\endgroup\$ Commented Aug 13, 2021 at 2:30
  • 1
    \$\begingroup\$ 117 bytes: does this work well? \$\endgroup\$ Commented Aug 16, 2021 at 3:55
2
\$\begingroup\$

Clam, 11 8 bytes

p=QrwQpQ 

Try it online!

-3 bytes thanks to the Q global variable

Storing variables is a tad verbose in Clam...

Explanation

p=QrwQpQ p Print.. = Assignment.. Q Global variable Q r Read next line of STDIN (automatically parsed to int if possible) w While.. Q Q is truthy pQ Print Q 

Resulting JS code:

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

AHHH, 24 bytes

AHHHHhHHhhHHHHHHhhHHhhhh 

AHHH is a somewhat more capable BF derivative in which every program consists of screaming.

Try it online!

Explanation

AHHH Begin program HhHH Read int into current cell hhHH Write current cell's value as int HHHH Loop while current cell is not zero hhHH Write current cell's value as int hhhh End loop 
\$\endgroup\$
2
\$\begingroup\$

Desmos, 33 bytes

n->ni+1,o->[1...n]0+i i=0 o=0 n=0 

The top line goes in a ticker, while the other lines are regular equations.

The input goes in variable i, while the output is shown in variable o.

Press the ticker (metronome icon) to start running the code.

Try It On Desmos!

Explanation

n->ni+1: If i=0, it becomes n->1, so n will always stay at 1. If i=1, it becomes n->n+1, so n will infinitely increment by 1.

o->[1...n]0+i: [1...n]0 creates a list of zeroes with length n. As shown with n->ni+1, if i=0, the length will always stay at 1; otherwise, it will keep increasing. +i simply converts the list of zeroes to a list of i's. So in summary, if i=0, then the list stays at length 1 and is populated with 0's. If i=1, then the list length is always increasing and is populated with 1's.

The rest of the code: It is simply to define the variables used in the actions above.

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

dotcomma, 8 bytes

[,].[.,] 

Try it online!

Dotcomma is a language I recently invented, designed to do things in an interesting way with as few instructions as possible. In order to accomplish this, there are two operators (predictably . and ,) which can do entirely different things depending on context. This answer's explanation will be very introductory. To see some more complicated code, check out the examples in the page linked in the title.

This program is actually a pretty neat showcase of some of the more interesting features of dotcomma. You'll notice it's divides into two main parts, [,] and [.,], separated by a .. These are called blocks. Every block and operator has a return value.

The way dotcomma manages to do so many different things with each operator is by changing what they do based on what precedes and follows them. Take the , in the first block. Because it is at the start of a block, its return value will be a value taken from input. Because it is at the end of a block, it will also output this value and use it as the block's return value. Surprisingly compact for a language with four valid characters!

As for the first ., because it is preceded by a block, it will take the block's return value and use it as its own. It is followed by another block, so it will do one two things: if its return value is 0, the block will be skipped. Thus, only 0 will be outputted and the program will terminate.

However, if its return value is 1, the block will be looped. Within the block are two operators: .,. The . will have a return value of 1, as it follows the beginning of a block. The , will behave similarly to the first one, but instead of taking the number to be outputted from input, it will take it from the . (which will always be 1). The loop will run forever because the , will always set the looped block's return value to 1.

Hopefully this explanation isn't too confusing!

\$\endgroup\$
1
  • \$\begingroup\$ Why didn't I upvote this until now????? Every single Dotcomma answer needs an upvote. \$\endgroup\$ Commented Apr 15, 2022 at 13:36
2
\$\begingroup\$

tinylisp, 31 bytes

(d A(q((N)(i N(A(c 1(disp 1)))0 

Defines a function A that takes the required input, as tinylisp has no concept of program input.

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could if you so wanted replace all of the digits with N ;-) \$\endgroup\$ Commented Apr 22, 2022 at 14:38
2
\$\begingroup\$

PostScript, 36 bytes

.runstdin 0 eq{0 =}{{1 =}loop}ifelse 

Probably needs to be run through ghostscript to get the .runstdin operator.

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

Shell (posix), 26 bytes (code) + 1 (input) = 27 bytes

run:

$ ./<name> <1 or 0> 

code:

[ $1 = 1 ]&&yes 1||echo 0 

Explained:

[ $1 = 1 ] is a hacky way of evaluating if argv[1] is equal to 1

in bash && executes if the previous command finishes with exit code 0

yes 1 yes is a command that takes in a string and prints continually to stdout

in bash || executes if the previous command finishes with a non-zero exit code

echo 0 self explainatory.

Old versions

[ $1 -eq 1 ]&&yes 1||echo 0 
[ $1 == 1 ]&&yes 1||echo 0 
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Commented Aug 10, 2022 at 18:21
2
\$\begingroup\$

Brainfuck, 5 Bytes

,.[.] 

I/O is as 0x00 / 0x01 bytes.

I just think it's a neat thing.

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

Leaf-Lang, 43 Bytes

Note: Link to interpreter is liked above.

code:

input toNumber 1=while 1 print stop 0 print 
\$\endgroup\$
2
\$\begingroup\$

hyperscript, 39 bytes

init log prompt()repeat while it log it 

Full program

hyperscript, 44 bytes

def f(n)repeat while n>0 log n end log n end 

Function

<script src="https://unpkg.com/[email protected]"></script> <script type="text/hyperscript"> def f(n)repeat while n>0 log n end log n </script> <label style="font-family:monospace">n: <input type="number"style="font-size:1.5rem;width:4.5ch"_="on change call f(my value)" /></label>

(Note: it will crash if you give it 1)

AFAIK hyperscript can't take input from STDIN, so I'm using a function instead.

Ungolfed:

def f(n) repeat while n > 0 log n end log n end 
\$\endgroup\$
1
  • \$\begingroup\$ 39 byte “full program”: init log prompt()repeat while it log it \$\endgroup\$ Commented Jun 12, 2023 at 19:45
2
\$\begingroup\$

shell, 28 bytes

[ 0 -eq $1 ]&&echo 0||yes 1 
\$\endgroup\$
2
\$\begingroup\$

Qdeql, 678 531 273 bytes

&------------------------------------------------\=-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\-=-\/\/==/*/------------------------------------------------\=/=\--\/\/=/* 

-147 by computing the ASCII 0 as (0 - 208) rather than putting 48 directly
-258 by computing the ASCII 1 similarly

Explanation:

& get input ---------- ---------- ---------- ---------- -------- subtract 48 \ while not 0: queue must be 1 0 0 now = skip the 1 get an ASCII 1: -==-==-==-==-==-==-==-==-==-== -==-==-==-==-==-==-==-==-==-== -==-==-==-==-==-==-==-==-==-== -==-==-==-==-==-==-==-==-==-== -==-==-==-==-==-==-==-==-== \-=-\/\/==/ * print the ASCII 1 / end while get an ASCII 0: ---------- ---------- ---------- ---------- -------- \=/= \--\/\/=/ * print it 

Motivation is a funny thing. If you had asked me last year if I wanted to write Qdeql code the answer would be no. But I need test cases for my interpreter, and Ørjan's transpiler from Brainfuck generates code that's too verbose to run in a reasonable amount of time.

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

MAWP v1.1, 18 14 bytes

@A{1A:.}1M[!:] 

-4 bytes with integer input.

Try it!

\$\endgroup\$
2
  • \$\begingroup\$ Nice answer! You should specify it is MAWP 0.1 (0.0 is not allowed, by the way, because it is not a programming langauge at all). \$\endgroup\$ Commented Aug 5, 2020 at 13:51
  • \$\begingroup\$ OH, sorry about that, I just used the answer generator here: 8dion8.github.io \$\endgroup\$ Commented Aug 5, 2020 at 15:18
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\$

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\$
1
  • \$\begingroup\$ Yes, you are correct. \$\endgroup\$ Commented Jan 16, 2016 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\$
7
  • \$\begingroup\$ n is already 0 or 1 after you read it. n=!!n does nothing at all! \$\endgroup\$ Commented Nov 4, 2015 at 2:15
  • \$\begingroup\$ Oh so I needn't account for situations where STDIN contains numbers that aren't 0 or 1? \$\endgroup\$ Commented Nov 4, 2015 at 2:18
  • \$\begingroup\$ 0 and 1 are the only possible inputs. \$\endgroup\$ Commented Nov 4, 2015 at 2:22
  • \$\begingroup\$ Sweet! Thanks for letting me know! I will update my answer. \$\endgroup\$ Commented Nov 4, 2015 at 2:22
  • \$\begingroup\$ You can remove the space before <iostream>, saving 1 byte. \$\endgroup\$ Commented Nov 4, 2015 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\$
3
  • \$\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\$ Commented Nov 7, 2015 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\$ Commented Nov 7, 2015 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\$ Commented Nov 7, 2015 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\$
2
  • \$\begingroup\$ Could you add an explanation? \$\endgroup\$ Commented Nov 4, 2015 at 12:45
  • \$\begingroup\$ @VoteToClose Done \$\endgroup\$ Commented Nov 4, 2015 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
6 7
8
9 10
17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.